pageContext對象是JSP中很重要的一個內置對象;
1.pageContext對象存取其他隱含對象屬性的方法,此時需要指定范圍的參數。
getAttribute(String name):取得page范圍內的name屬性。
setAttribute(String name, Object value, int scope):如果沒有指定scope,該屬性默認在page范圍內,如:pageContext.setAttribute("page","hello");
范圍參數有四個,分別代表四種范圍:PAGE_SCOPE、REQUEST_SCOPE、SESSION_SCOPE、APPLICATION_SCOPE
2.實例
<%@page contentType="text/html;charset=gb2312"%> <html><head><title>pageContext對象_例1</title></head> <body><br> <% //使用pageContext設置屬性,該屬性默認在page范圍內 pageContext.setAttribute("name","jason test"); request.setAttribute("name","霖苑編程"); session.setAttribute("name","霖苑計算機編程技術培訓"); //session.putValue("name","計算機編程"); application.setAttribute("name","培訓"); %> page設定的值:<%=pageContext.getAttribute("name")%><br> request設定的值:<%=pageContext.getRequest().getAttribute("name")%><br> session設定的值:<%=pageContext.getSession().getAttribute("name")%><br> application設定的值:<%=pageContext.getServletContext().getAttribute("name")%><br> 范圍1內的值:<%=pageContext.getAttribute("name",1)%><br> 范圍2內的值:<%=pageContext.getAttribute("name",2)%><br> 范圍3內的值:<%=pageContext.getAttribute("name",3)%><br> 范圍4內的值:<%=pageContext.getAttribute("name",4)%><br> <!--從最小的范圍page開始,然后是reques、session以及application--> <%pageContext.removeAttribute("name",3);%> pageContext修改后的session設定的值:<%=session.getValue("name")%><br> <%pageContext.setAttribute("name","應用技術培訓",4);%> pageContext修改后的application設定的值:<%=pageContext.getServletContext().getAttribute("name")%><br> 值的查找:<%=pageContext.findAttribute("name")%><br> 屬性name的范圍:<%=pageContext.getAttributesScope("name")%><br> </body></html>
3.顯示結果
page設定的值:jason test request設定的值:霖苑編程 session設定的值:霖苑計算機編程技術培訓 application設定的值:培訓 范圍1內的值:jason test 范圍2內的值:霖苑編程 范圍3內的值:霖苑計算機編程技術培訓 范圍4內的值:培訓 pageContext修改后的session設定的值:null pageContext修改后的application設定的值:應用技術培訓 值的查找:jason test 屬性name的范圍:1
