jsp页面是通过jsp引擎转化为servlet的,在转化的过程中,jsp引擎会创建或传递九个web开发对象供开发者使用,今天我就来介绍一下jsp中的九大内置对象。
jsp中的内置九大对象分别是:request,response,session,application,out,page,pageContext,config,exception。其中,request表示的就是HttpServletRequest对象,response表示的就是HttpServletResponse对象,session表示的就是HttpSession对象,application表示的就是ServletContext对象,page表示的就是当前jsp页面对象也就是this,config表示ServletConfig对象。这几个对象我都在servlet中介绍过了,所以我今天主要介绍out和pageContext变量所对应的对象。
一、out
out变量在jsp页面表示JspWriter对象,相当于带缓存功能的PrintWriter。使用out的输出时,首先会把输出的内容写在缓冲区中而不是直接输出到浏览器上,只有当缓存区的数据满了或者用户手动清除缓存区或者jsp脚本加载完毕后才会把缓存区的数据输出到浏览器上。我们可以通过out.getBufferSize()和out.getRemaining()获取缓冲区的大小和缓冲区的剩余大小。我们也是自己设置缓冲区的大小通过<%@ page buffer="5kb"%>设置。例如:
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <%@ page buffer="5kb"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; utf-8"> <title>Insert title here</title> </head> <body> <% out.println("test out<br/>"); response.getWriter().println("test prints<br/>"); response.getWriter().println("缓冲区的大小是:"+ out.getBufferSize()+"<br/>"); response.getWriter().println("缓冲区的剩余大小是:"+ out.getRemaining()+"<br/>"); %> </body> </html>
二、PageContext
PageContext对象包含了其他八个对象的引用同时PageContext对象还是一个域对象,使用PageContext对象可以直接给不同的域设置值。
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Insert title here</title> </head> <body> <% out.write( (pageContext.getRequest() == request ) + "<br/>"); out.write( (pageContext.getResponse() == response ) + "<br/>"); out.write( (pageContext.getSession() == session ) + "<br/>"); out.write( (pageContext.getServletConfig() == config ) + "<br/>"); out.write( (pageContext.getServletContext() == application ) + "<br/>"); out.write( (pageContext.getPage() == page ) + "<br/>"); out.write( (pageContext.getOut() == out ) + "<br/>"); out.write("<hr/>"); pageContext.setAttribute("page","currentpage"); pageContext.setAttribute("name","jack",pageContext.REQUEST_SCOPE); pageContext.setAttribute("age","38",pageContext.SESSION_SCOPE); pageContext.setAttribute("sex","man",pageContext.APPLICATION_SCOPE); out.write( pageContext.getAttribute("page") + "<br/>"); out.write( request.getAttribute("name") + "<br/>"); out.write( session.getAttribute("age") + "<br/>"); out.write( application.getAttribute("sex") + "<br/>"); %> </body> </html>
三、四大作用域
在jsp中有四大作用域分别是:page,request,session,application。其中page表示的是只在当前页面有效,reqeust表示客户端的一次请求中有效,session表示用户的一次会话中有效,application表示在整个web服务中有效。