jsp中的out输出和response.getWriter输出的区别
response中表示响应,我们经常用于设置返回给客户端的内容〈输出),out也是给用户做输出使用的。
一、当jsp页面中所有代码执行完成后会做以下两个操作:
- 执行out.flush操作,会把out缓冲区中的数据追加写入到response缓冲区末尾
- 会执行response的刷新操作。把全部数据写给客户端
二、由于jsp翻译之后,底层源代码都是使用out 来进行输出,所以一般情况下。我们在jsp页面中统一使用out 来进行输出。避免打乱页面输出内容的顺序。
out.write()和out.print()区别
out.write():输出字符串没有问题
out.print():输出任意数据都没有问题(都转换成为字符串后调用的write输出)
深入源码,浅出结论:在jsp页面中,可以统一使用out.print()来进行输出
- print方法是子类JspWriter中定义的方法,write是Writer类中定义的方法;
- write():仅支持输出字符类型数据,字符、字符数组、字符串等
print():可以将各种类型(包括Object)的数据,通过默认编码转换成bytes字节形式,这些字节都通过write(int c)方法被输出 - JspWriter类型的out对象使用print方法和write方法都可以输出字符串,但是,如果字符串对象的值为null时,print方法将输出内容为“null”的字符串,而write方法则是抛出NullPointerException异常。
<%--
Created by IntelliJ IDEA.
User: 20186
Date: 2021/11/17
Time: 18:33
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%
out.write("out输出1");
response.getWriter().write("response输出1<br/>");
response.getWriter().write("response输出2<br/>");
out.write("out输出2");
out.write(12); //无法正常输出
out.print(12); //可以输出
%>
</body>
</html>