tags:

views:

252

answers:

3

When defining a function for the JSP expression language, is there a way to specify that the function requires one of the implicit objects (such as pageContext)?

I want to define a function ${my:href('a.jpg')} to be implemented by

public static String href(String fileName, PageContext pageContext)

but I do not want to have to explicitly pass the pageContext to the function every time I call it.

+1  A: 

It would be nice but no, there is no way to do that directly. Also, there is no workaround since JSP EL functions must be public static. So the solution is to go back to plain old JSP code:

<% Helper my= new Helper (pageContext); %>

Helper has a normal public method that takes a filename as argument:

public String href (String fileName) { ... }

and later

... ${my.href(...)}
Aaron Digulla
There's no way to do it directly, but it's definitely possible to do it, and I make use of that extensively in my Java web app.
Pointy
A: 

You can access the "implicit" objects only if you provide for stashing them (via a filter or something) as thread local variables. Then you can write some utility classes to go get them from whatever context makes sense. Some frameworks (Stripes, for example) (yaay Stripes!) make that relatively easy.

Pointy
So you put the info object in some context (which probably uses a hash map somewhere). This makes it easy to locate the info object from anywhere but it's slow. My solution is much faster but less flexible.
Aaron Digulla
It's not slow, and you don't need to put them in a hash map. (Well, not an explicit hash map, or a visible one anyway; it's all a matter of how ThreadLocal is implemented.) You can use individual ThreadLocal variables to store different context objects, and access them via utility classes (singletons or static accessor functions). Strips lets you keep a single general context object around, from which you can get at anything you might need.
Pointy
+1  A: 

Consider using a tag instead of a function. Tags provides you implicit access to the PageContext by the inherited TagSupport#pageContext.

BalusC
Yeah, I have a tag now, but I wanted to convert it to a function because `<a <my:href href='a.png' /> >` offends my XML sensibilities. And I did not want to go all the way and implement a complete `<my:a>` tag.
Thilo