Using the PageContext API for tag handlers

This page is just a review from what you saw in the Script-free JSPs chapter, but it comes up again here because it’s crucial for a tag handler. A tag handler class, remember, is not a servlet or a JSP, so it doesn’t have automatic access to a bunch of implicit objects. But it does get a reference to a PageContext, and with it, it can get to all kinds of things it might need.

Remember that while Simple tags get a reference to a JspContext and Classic tags get a reference to a PageContext, the Simple tag’s JspContext is usually a PageContext instance. So if your Simple tag handler needs access to PageContext-specific methods or fields, you’ll have to cast it from a JspContext to the PageContext it really is on the heap.

image with no caption

Note

The one-arg getAttribute(String) is for page scope ONLY!

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.

Note

findAttribute() looks in EACH scope starting with PAGE_SCOPE.

You can expect to be tested on this!! The difference between getAttribute(String) and findAttribute(String) can be dramatic—the getAttribute(String) method looks ONLY ...

Get Head First Servlets and JSP, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.