Reputation: 73
I have a JSP file called header.jsp which looks like this.
<%@ taglib prefix="c" uri="/c" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<!DOCTYPE html>
<html>
<head>
...
</head>
<body>
I then have a content fragment which looks like this.
<jsp:include page="../header.jsp" />
My Page Content Here.
If that content fragment has certain dependencies like CSS and Javascript includes which have to go inside the head tag, how can I include them there? Each fragment might have its own set of CSS and Javascript files which are different, and I don't want to include every single possible CSS and Javascript file I might use into the header for every single page. What's the proper way to handle this? I'm a dumb intern at a startup, so forgive my ignorance. Thank you in advanced.
Upvotes: 4
Views: 4115
Reputation: 5892
It's easy, you can do the following by using <jsp:invoke />
tag instead of the <include />
tag. It's new for jsp 2.0 and allows you to take some fragments from one page to another, making very easy the task of building templates. You can check a tutorial here.
And this is the way to solve your problem: Create a tag folder and put this in it.
template.tag
<%@tag description="Main template of the page" pageEncoding="UTF-8" trimDirectiveWhitespaces="true" %>
<%@attribute name="header" fragment="true" required="false" %>
<html>
<head>
...some css and javasctipt used on all the pages...
<!-- Custom css and javascript for one page -->
<jsp:invoke fragment="header"/>
</head>
<body>
<jsp:doBody />
</body>
</html>
Use the previous template on your page by including the tag folder:
useOfTemplate.jsp
<%@page contentType="text/html" pageEncoding="UTF-8" %>
<%@taglib prefix="custom" tagdir="/WEB-INF/tags" %>
<custom:template>
<jsp:attribute name="header">
...Here you can include your custom css and javascript for this page...
</jsp:attribute>
<jsp:body>
...here comes the info of the page...
</jsp:body>
</custom:template>
Upvotes: 4