jBoive
jBoive

Reputation: 1299

Include a JSP file in another JSP file and modify the parent HEAD or BODY?

Using: Apache Tomcat 6 Spring 4.0

Let's say I have a "child" JSP file that contains a link to an external javascript file:

I then include the child.jsp in the middle of my parent JSP-file the resulting HTML would be something similar to below:

<html>
<head></head>
<body>
<lotsOfHTML>
<!-- start injected JSP -->
<injectedHTML>
  <script src="my-external-file.js"></script>
<!-- end injected JSP -->
<evenMoreHTML>
</body>
</html>

What I want is:

<html>
<head></head>
<body>
<lotsOfHTML>
<!-- start injected JSP -->
<injectedHTML>
<!-- end injected JSP -->
<evenMoreHTML>
  <script src="my-external-file.js"></script>  <-- Injected Javascript
</body>
</html>

Clarifying:

This is what my JSPs looks like:

index.jsp include1.jsp indclude2.jsp

index.jsp has the meat of the page, like the header and such. include1.jsp and include2.jsp contains stuff like widgets and other components that I wish to reuse on my pages. This includes CSS and JavaScript libraries.

By default any included references to external CSS and JavaScript would be included in the middle of the page. I want the JavaScript libraries to appear at the bottom of the page that the includeX.jsp is included on.

How can I achieve this? Worst case(?) would be to include the JavaScript file in the HEAD, but preferably at the bottom of the BODY-tag.

Thanks!

/J

Upvotes: 1

Views: 2187

Answers (2)

user2575725
user2575725

Reputation:

This solution is a way around for your requirement. Go for two jsp page, header.jsp, which imports all .css files. footer.jsp for importing .js files. Now configure your web.xml to make use of these jsp page throughout the webapp.

<jsp-config>
   <jsp-property-group>
     <url-pattern>*.jsp</url-pattern>
     <el-ignored>false</el-ignored>
     <scripting-invalid>false</scripting-invalid>
     <is-xml>false</is-xml>
     <include-prelude>/template/header.jsp</include-prelude> <!-- header -->
     <include-coda>/template/footer.jsp</include-coda> <!-- footer -->
   </jsp-property-group>
 </jsp-config>

Upvotes: 0

woemler
woemler

Reputation: 7169

This can be accomplished using JSP tag files. For example:

index.jsp

<%@ taglib prefix="my-tags" tagdir="/WEB-INF/tags" %>
<html>
    <head>
        <!-- Stuff goes here -->
    </head>
    <body>
       <!-- Content goes here -->
       <my-tags:javascript />
    </body>
</html>

javascript.tag

<%@tag description="JavaScript libraries for all pages." pageEncoding="UTF-8"%>
<script type="text/javascript" src="/static/jquery.js"></script>

When index.jsp gets processed into HTML by Tomcat, the contents of your tag files will be injected into the JSP. You could also wrap the tag reference in a conditional EL evaluation, if you don't always want the JS injected into the page.

Upvotes: 3

Related Questions