O'Reilly logo

Head First Servlets and JSP, 2nd Edition by Bert Bates, Bryan Basham, Kathy Sierra

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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) ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required