Setting a page-scoped attribute
<% Float one = new Float(42.5); %>
<% pageContext.setAttribute("foo", one); %>
pageContext getAttribute(String) is for page scope
There are TWO overloaded getAttribute() methods you can call on pageContext: a one-arg that takes a String, and a two-arg that takes a String and an int. The one-arg version works just like all the others—it’s for attributes bound TO the pageContext object. But the two-arg version can be used to get an attribute from ANY of the four scopes.
Getting a page-scoped attribute
<%= pageContext.getAttribute("foo") %>
Using the pageContext to set a session-scoped attribute
<% Float two = new Float(22.4); %> <% pageContext.setAttribute("foo", two, PageContext.SESSION_SCOPE); %>
Using the pageContext to get a session-scoped attribute
<%= pageContext.getAttribute("foo", PageContext.SESSION_SCOPE) %> (Which is identical to: <%= session.getAttribute("foo") %> )
Using the pageContext to get an application-scoped attribute
Email is: <%= pageContext.getAttribute("mail", PageContext.APPLICATION_SCOPE) %>
Within a JSP, the code above is identical to:
Email is:
<%= application.getAttribute("mail") %>
Using the pageContext to find an attribute when you don’t know the scope
<%= pageContext.findAttribute("foo") %>
Where does the findAttribute() method look? It looks first in the page context, so if there’s a “foo” attribute with page context scope, then calling findAttribute(String name) on a PageContext works just like calling getAttribute(String name) on a PageContext. But if there’s no “foo” attribute, the method starts looking in other scopes, from most restricted to least restricted scope —in other words, first request scope, then session, then finally application scope. The first one it finds with that name wins.