Examples using pageContext to get and set attributes
Setting a page-scoped attribute
<% Float one = new Float(42.5); %>
<% pageContext.setAttribute("foo", one); %>Note
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") %>Note
find it where?
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) ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access