PageContext

In a JSP page we can access, through implicit objects, four different context, we already know three of them (application, request, session), as we talked about servlets. Here we talk about the page one, that is just for JSP.

In a JSP page, we can store an object as attribute in one of these four scopes:
<%
    String app = "application";
    application.setAttribute("attApp", app);

    String req = "request";
    request.setAttribute("attReq", req);

    String ses = "session";
    session.setAttribute("attSes", ses);

    String pag = "page";
    pageContext.setAttribute("attPag", pag);
%>
To retrieve an attribute we can call the getAttribute() method on the relative implicit object, or specifying the required scope for the getAttribute() on the pageContext:
<br />Attribute in page: <%= pageContext.getAttribute("attPag") %>
    <br />Attribute in request: <%= pageContext.getAttribute("attReq", PageContext.REQUEST_SCOPE) %>
    <br />Attribute in request /2: <%= request.getAttribute("attReq") %>
    <br />Attribute in session: <%= pageContext.getAttribute("attSes", PageContext.SESSION_SCOPE) %>
    <br />Attribute in session /2: <%= session.getAttribute("attSes") %>
    <br />Attribute in application: <%= pageContext.getAttribute("attApp",     PageContext.APPLICATION_SCOPE) %>
<br />Attribute in application /2: <%= application.getAttribute("attApp") %>
And we can also use the findAttribute() method on the page, that would scan the scopes looking for the required attribute (in page, then request, session, and at the end in the application scope):
<br />Find attribute: <%= pageContext.findAttribute("attPag") %>
<br />Find attribute /2: <%= pageContext.findAttribute("attReq") %>
<br />Find attribute /3: <%= pageContext.findAttribute("attSes") %>
<br />Find attribute /4: <%= pageContext.findAttribute("attApp") %>
I wrote this post while I was reading the seventh chapter of Head First Servlet and JSP. You should read it to learn more on this stuff (and have some fun too).

No comments:

Post a Comment