目录
4.jsp中的out输出和response.getWriter输出的区别
1.jsp的三种注释
1.html注释 <--! html注释 -->
html注释会被翻译到java源代码中。在_jspService方法里,以out.writer输出到客户端。
2.java注释
<% //单行java注释 /* 多行java注释 */ %>
java注释会被翻译到java源代码中。
3.jsp注释
<%-- 这是jsp注释 --%>
jsp注释可以注解掉jsp页面中的所有代码。
2.jsp九大内置对象
jsp中的内置对象,是指Tomcat在翻译jsp页面成为Servlet源码后,内部提供的九大对象,叫做内置对象。
1.request 请求对象
2.response 响应对象
3.pageContext jsp的上下文对象
4.session 会话对象
5.application ServletContext对象
6.config ServletConfig对象
7.out jsp输出流对象
8.page 指向当前jsp的对象
9.exception 异常对象
3.jsp四大域对象
四个域对象分别是:
pageContext(PageContext类),当前jsp页面范围内有效;
request(HttpServletRequest类),一次请求内有效;
session(HttpSession类),一个会话范围有效(打开浏览器访问服务器,直到关闭浏览 器)
application(ServletContext类);整个web工程范围内有效(只要web工程不停止,数据都 在)
域对象是可以像Map一样存取数据的对象。四个域对象功能一样。不同的是它们对数据的存取范围。
虽然四个域对象都可以存取数据,在使用上是有优先级顺序的。
pageContext ==>> request == >> session ===>> application 不用的时候可以对内存进行释放。
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2021/12/8
Time: 20:02
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>
<h1>scope.jsp页面</h1>
<%
//往四个域中分别保存了数据
pageContext.setAttribute("key","pageContext1");
request.setAttribute("key","request2");
session.setAttribute("key","session3");
application.setAttribute("key","application4");
%>
pageContext域是否有值:<%= pageContext.getAttribute("key")%>
request域是否有值:<%=request.getAttribute("key") %>
session域是否有值:<%=session.getAttribute("key") %>
application域是否有值:<%=application.getAttribute("key") %>
<%
request.getRequestDispatcher("/scope2.jsp").forward(request,response);
%>
</body>
</html>
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2021/12/8
Time: 20:02
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>
<h1>scope2.jsp页面</h1>
<%
//往四个域中分别保存了数据
%>
pageContext域是否有值:<%= pageContext.getAttribute("key")%>
request域是否有值:<%=request.getAttribute("key") %>
session域是否有值:<%=session.getAttribute("key") %>
application域是否有值:<%=application.getAttribute("key") %>
</body>
</html>
4.jsp中的out输出和response.getWriter输出的区别
response中表示响应,我们经常用于设置返回给客户端的内容(输出);
out也是也给用户输出使用的。
<%
out.write("out输出1 <br/>");
out.write("out输出2 <br/>");
response.getWriter().write("response输出1 <br/>");
response.getWriter().write("response输出2 <br/>");
%>
输出结果:
response输出1
response输出2
out输出1
out输出2
<%
out.write("out输出1 <br/>");
out.flush();
out.write("out输出2 <br/>");
response.getWriter().write("response输出1 <br/>");
response.getWriter().write("response输出2 <br/>");
%>
输出结果:
由于jsp翻译之后,底层源代码都是使用out来进行输出,所以一般情况下,我们在jsp页面中统一使用out进行输出。避免打乱页面输出内容顺序。
out.write() 输出字符串没有问题
out.print() 输出任意数据都没有问题。(都转化成字符串后调用的write()输出);
深入源码,浅出结论:在jsp页面中,可以统一使用out.print() 来进行输出。