JSP中page和pageContext的区别

来源:互联网 发布:淘宝几个好评一颗心 编辑:程序博客网 时间:2024/05/16 04:12

 page java.lang.Object  对应this关键字。JSP网页本身,page对象是当前页面转换后的Servlet类的实例。从转换后的Servlet类的代码中,可以看到这种关系:Object page = this;在JSP页面中,很少使用page对象。

  pageContext  javax.servlet.jsp.PageContext 的实例,该对象代表该JSP 页面上下文,使用该对象可以访问页面中的共享数据。常用的方法有getServletContext和getServletConfig等。

Java代码  收藏代码
  1. //使用pageContext 设置属性,该属性默认在page 范围内  
  2. pageContext. setAttribute ("page" , "hello") ;  
  3.   
  4. //使用request 设置属性,该属性默认在request 范围内  
  5. request. setAttribute ("request" , "hello");  
  6.   
  7. //使用pageContext将属性设置在request 范围中  
  8. pageContext.setAttribute("request2″ , "hello" , pageContext.REQUEST_SCOPE);  
  9.   
  10. //使用session将属性设置在session 范围中  
  11. session.setAttribute("session" , "hello");  
  12.   
  13. //使用pageContext将属性设置在session范围中  
  14. pageContext.setAttribute("session2″ , "hello" , pageContext.SESSION_SCOPE);  
  15.   
  16. //使用application将属性设置在application范围中  
  17. application. setAttribute ("app" , "hello") ;  
  18.   
  19. //使用pageContext 将属性设置在application 范围中  
  20. pageContext.setAttribute("app2″ , "hello" , pageContext.APPLICATION_SCOPE) ;   

PageContext对象

1.pageContext对象是javax.servlet.jsp.PageContext类的实例,主要表示的是一个JSP页面的上下文。

2.pageContext对象有如下一些方法:

(1)页面跳转

public abstract void forward(String relativeUrlPath)throws ServletException, IOException

(2)页面包含

public void include(String relativeUrlPath) throws ServletException, IOException

(3)取得ServletConfig对象

public ServletConfig getServletConfig()

(4)取得ServletContext对象

public ServletContext getServletContext()

(5)取得ServletRequest对象

public ServletRequest getRequest()

(6)取得ServletResponse对象

public ServletResponse getResponse()

(7)取得HttpSession对象

public HttpSession getSession()

样例:

pageContext_forward01.jsp

[plain] view plain copy
  1. <%@ page contentType="text/html" pageEncoding="GBK"%>  
  2. <html>  
  3. <head><title>欢迎来到望星空</title></head>  
  4. <body>  
  5. <%  
  6.     pageContext.forward("pageContext_forward02.jsp?info=Joywy");    <!-- 括号内?左右不要有空格,否则会报出HTTP Status 404 -->  
  7. %>  
  8. </body>  
  9. </html>  
pageContext_forward02.jsp

[plain] view plain copy
  1. <%@ page contentType="text/html" pageEncoding="GBK"%>  
  2. <html>  
  3. <head><title>欢迎来到望星空</title></head>  
  4. <body>  
  5. <%  
  6.     //直接从pageContext对象中取得了request  
  7.     String info = pageContext.getRequest().getParameter("info");  
  8. %>  
  9. <h3>info = <%=info%></h3>  
  10. <h3>realpath = <%=pageContext.getServletContext().getRealPath("/")%></h3>  
  11. </body>   
  12. </html>  
注意:取得的操作实际上是request和response对象所在接口的父接口实例。

pageContext对象中的getRequest()和getResponse()两个方法返回的是ServletRequest和ServletResponse,而常用的request和response分别是HttpServletRequest和HttpServletResponse接口的实例。







0 0