Can a JSP tag file access its calling JSP's PageContext?
Asked Answered
K

2

11

If I do:

<% pageContext.setAttribute("foo", "bar"); %>
<custom:myTag/>

it seems like I should be able to do:

<%= pageContext.getAttribute("foo") %>

inside of myTag.tag ... but of course I can't because the tag file doesn't have access to the pageContext (instead it has access to a jspContext ... which doesn't have the same attributes as the calling page's pageContext).

Now, you can access the pageContext via ELScript:

${pageContext}

but that doesn't help because ELScript has no way of passing arguments, so you can't do:

${pageContext.getAttribute("foo")}

However, the fact that ELscript can accesss the page context, and the fact that the tag can access all sorts of variables like jspContext, that there must be some way for a tag to access (in a scriptlet/Java logic way, not just in ELScript) an attribute from the calling JSP's pageContext.

Is there?

Keegan answered 17/8, 2011 at 19:11 Comment(0)
B
8

As to EL, the ${pageContext.getAttribute("foo")} works in EL 2.2 only. Before that the right syntax is ${pageContext.foo} or just ${foo}. See also our EL wiki page.

However, the ${pageContext} isn't shared between the parent JSP file and the JSP tag. Each has its own instance.

You could either set it as request attribute instead:

<% request.setAttribute("foo", "bar") %>
<custom:myTag />

with in the tag

<%= request.getAttribute("foo") %>

or, with EL

${requestScope.foo}

or

${foo}

Or, better, you could pass it as a fullworthy tag attribute

<custom:myTag foo="bar" />

with in the tag

<%@attribute name="foo" required="true" %>
${pageContext.foo}

or just

<%@attribute name="foo" required="true" %>
${foo}
Bentz answered 17/8, 2011 at 19:45 Comment(3)
Thanks, but the thing is, I've already got the variables i want in the pageContext, and enough (legacy) code that references them there that I don't want to have to change them to request attributes. So I can just put duplicate copies in to the request too, but I was hoping there was some other way to do it. Oh, and these variables are going to get passed A LOT in A LOT of tags if I make them attributes, so I was really hoping for a "behind the scenes" solution. If there is no way possible to access the JSP's pageContext from the tag though ... guess I'm out of luck :-(Keegan
You can just access the actual page context with (PageContext)getJspContext(). See my answer below.Baal
@Jason: question wasn't about that.Bentz
P
1

Looks like in WebLogic 10 at least, the implicit "application" object is available in tag files, and is instanceof ServletContext. Maybe use this, when it's really the ServletContext that one is after, and not necessarily the higher-level pageContext.

Proclaim answered 23/5, 2013 at 15:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.