40

Possible Duplicate:
JSP tricks to make templating easier?

I'm new to JSPs and Servlets, I'm wondering is there a neat way to create a layout jsp and reuse it on similar jsp pages, something like asp.net master pages.

I googled it, some people say use templates http://java.sun.com/developer/technicalArticles/javaserverpages/jsp_templates that uses jstl tag library. It says to put a tag like this:

<%@ taglib uri='/WEB-INF/tlds/template.tld' prefix='template' %>

but I get error (because jstl.jar and standard.jar are in WEB-INF/lib/ directory).

However some say jstl template have problems according to this Struts OR Tiles OR ???...... JSP template solution

I would be glad to help me know the best way.

EDIT: What I need is to split page's layout into parts like content, header,... and set this parts in the page that uses the layout template, exactly like asp.net master page.

Community
  • 1
  • 1
Ashkan
  • 3,322
  • 4
  • 36
  • 47
  • 1
    possible solution http://stackoverflow.com/questions/1296235/jsp-tricks-to-make-templating-easier http://www.javaworld.com/javaworld/jw-09-2000/jw-0915-jspweb.html i dont know the best way – shareef May 10 '12 at 08:19
  • thanks I think the first link is great http://stackoverflow.com/questions/1296235/jsp-tricks-to-make-templating-easier – Ashkan May 10 '12 at 08:31
  • This can also be achieved with jsp:include. Chad Darby explains well here in this video https://www.youtube.com/watch?v=EWbYj0qoNHo – Sandeep Amarnath Sep 24 '19 at 15:16

1 Answers1

94

Put the following in WEB-INF/tags/genericpage.tag

<%@tag description="Overall Page template" pageEncoding="UTF-8"%>
<%@attribute name="header" fragment="true" %>
<%@attribute name="footer" fragment="true" %>
<html>
  <body>
    <div id="pageheader">
      <jsp:invoke fragment="header"/>
    </div>
    <div id="body">
      <jsp:doBody/>
    </div>
    <div id="pagefooter">
      <jsp:invoke fragment="footer"/>
    </div>
  </body>
</html>

To use this:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="t" tagdir="/WEB-INF/tags" %>

<t:genericpage>
    <jsp:attribute name="header">
      <h1>Welcome</h1>
    </jsp:attribute>
    <jsp:attribute name="footer">
      <p id="copyright">Copyright 1927, Future Bits When There Be Bits Inc.</p>
    </jsp:attribute>
    <jsp:body>
        <p>Hi I'm the heart of the message</p>
    </jsp:body>
</t:genericpage>

That does exactly what you think it does!

This was part of a great answer by Will Hartung on this link.

Community
  • 1
  • 1
Ashkan
  • 3,322
  • 4
  • 36
  • 47