views:

48

answers:

2

When creating JSP pages one thing that I'd often like is the ability to do something like this:

<jsp:include page="fancystoryrenderer.jsp" value="${aStoryObjectInMyModel}/>

...

fancystoryrenderer.jsp

<div id="fancymainbody">
    ...
    ${theStory.title}
    ...
</div>

The main important characteristics of this is that I can reuse the same component on the same JSP page in different places without having to copy paste the component and give the story variables different names, notice that the story is called "theStory" in the JSP and not "aStoryObjectInMyModel", the linkage between our model has been broken by the view, which is a good thing in this case. Also, I know you can pass a parameter to the JSP view, but I DO NOT WANT to grab attributes from the request object at all, I want to be able to use the parameters from expression language.

How do you do this?

I am using Spring-MVC and JSP, please no added frameworks, I'm interested in getting this to work using only the web stack I currently have.

+2  A: 

Put the desired model in the request (or broader) scope and it'll just work without "passing" it around.

If the actual move behind this need is because you're including the page inside for example a JSTL c:forEach loop (which puts the currently iterated item in local scope which is indeed inaccessible to the included JSP page), then you can use c:set to set it.

<c:forEach items="${items}" var="item">
    <c:set var="currentitem" value="${item}" scope="request" />
    <jsp:include page="include.jsp" />
</c:forEach>

With in include.jsp:

<p>Current item: ${currentitem}</p>

It'll just work :)

BalusC
+2  A: 

This can be arhcives using so called "tag files". Tag files are basically jsps that are put under WEB-INF/tags and that can then be used like a taglib. I am using the xml syntax in this example but it should also work with the older syntax.

/WEB-INF/tags/mytag.jspx

<?xml version='1.0' encoding='utf-8'?>
<jsp:root version="2.1" xmlns:jsp="http://java.sun.com/JSP/Page"&gt;
    <jsp:directive.attribute name="mybean" required="true" rtexprvalue="true" type="mypackage.MyBean"/>
    <div>
       ${mybean.myproperty}
    </div>
</jsp:root>

test.jspx

<?xml version='1.0' encoding='utf-8'?>
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.1" xmlns:tags="urn:jsptagdir:/WEB-INF/tags/">
    <jsp:directive.page contentType="text/html; charset=utf-8"/>
    <div>
      <tags:mytag mybean="${mymodel.mybean}"/>
    </div>
</jsp:root>

You might also need a file implicit.tld in WEB-INF/tags to set the taglib version:

<?xml version='1.0' encoding='utf-8'?>
<taglib xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd"
    version="2.1" xmlns="http://java.sun.com/xml/ns/javaee"&gt;
    <tlib-version>2.1</tlib-version>
</taglib>
Jörn Horstmann