Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass a parameter to a JSP via a cross-context JSTL import?

Tags:

java

jsp

jstl

I've come across a few other questions that describe a similar, but not identical situation, to mine. This question, for instance, shows pretty much the same problem, except that I'm not using portlets - I'm just using boring ol' JSP+JSTL+EL+etc.

I have two application contexts, and I'd like to import a JSP from one to the other. I know how do that:

<c:import context="/" url="/WEB-INF/jsp/foo.jsp"/>

However, I also want to pass a parameter to the imported foo.jsp. But this code:

<c:import context="/" url="/WEB-INF/jsp/foo.jsp">
    <c:param name="someAttr" value="someValue"/>
</c:import>

does not seem to properly send the parameter to foo.jsp; if foo.jsp is something like*

<% System.out.println("foo.jsp sees that someAttr is: "
                      + pageContext.findAttribute("someAttr")); %>

then this gets printed out:

foo.jsp sees that someAttr is: null

whereas I want to see this:

foo.jsp sees that someAttr is: someValue

so, obviously, someAttr can't be found in foo.jsp.

How do I fix this?


*(yes, I know, scriplets==bad, this is just for debugging this one problem)

like image 991
Matt Ball Avatar asked Oct 13 '10 03:10

Matt Ball


People also ask

How will you pass parameters in JSP file from an HTML file with an example?

To pass the parameters from index to file page we are using <jsp:param> action tag. We are passing three parameters firstname, middlename and lastname, for each of these parameters we need to specify the corresponding parameter name and parameter value.


1 Answers

You're setting it as a request parameter, so you should also be getting it as request parameter.

Since you seem to dislike scriptlets as well, here's an EL solution:

${param.someAttr}

Note that <c:import> doesn't add any extra advantages above <jsp:include> in this particular case. It's useful whenever you want to import files from a different context or an entirely different domain, but this doesn't seem to be the case now. The following should also just have worked:

<jsp:include page="/WEB-INF/jsp/foo.jsp">
    <jsp:param name="someAttr" value="someValue" />
</jsp:include>

This way the included page has access to the same PageContext and HttpServletRequest as the main JSP. This may end up to be more useful.

like image 64
BalusC Avatar answered Oct 24 '22 01:10

BalusC