1

I'm doing a little website using Java EE and I'm experiencing a problem. In fact, I would like to have a main layout in which I would like to have the elements of my website which appear on each page. Something like that :

<html>
    <head>
        <title>Just a website...</title
    </head>
    <body>
        <div id="page">
            <div id="header"></div>
            <div id="content">
                <!-- Include content here -->
            </div>
            <div id="footer">
        </div>
    </body>
</html>

Then, when I go on a specific page, I would like that the content of that page would be include in the "content" bloc.

The problem is that I don't know what is the best way to do it. Do I have to create a main servlet and forward all requests from others servlets to that servlet and then handle the page that I have to include ?

I would be happy to find a tutoriel or something like that on the internet but I don't.

Arjan Tijms
  • 37,782
  • 12
  • 108
  • 140
  • 2
    It's easy with JSP's successor Facelets. See also http://stackoverflow.com/questions/4792862/how-to-include-another-xhtml-in-xhtml-using-jsf-2-0-facelets As to old JSP, see also this related question: http://stackoverflow.com/questions/1296235/jsp-tricks-to-make-templating-easier – BalusC Feb 29 '12 at 23:42

2 Answers2

3

You can use things like SiteMesh or Tiles, or simply use the jsp include mechanism, which is perfectly serviceable for simplistic templating.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
  • My problem is that I don't know how to handle that with the servlet. Actually, I have one servlet per page and I use that line of code in order to get the right page. `req.getRequestDispatcher("/jsp/account/addAccount.jsp").forward(req, resp);` So do I have to forward the requests from all my servlet to my main layout ? – Sylvain Ollivier Feb 29 '12 at 21:50
  • @SylvainOllivier No; did you look at the second example? – Dave Newton Feb 29 '12 at 22:39
1

You can simply use the <jsp:include> This is to include page at runtime (executed at request).

See also

MalsR
  • 1,197
  • 1
  • 12
  • 23
  • Ok, so I put a `` in my main layout... But how can my main layout can know which page he need to include ? – Sylvain Ollivier Feb 29 '12 at 21:44
  • Well for your simple example you could even use jstl condition to include which jsp page or depending on your intended pages modularise the jsps so you can even have a header and footer separate jsps and include them in your specific content pages. Again it will depend on your content/needs but I believe thse are perfect for simplistic cases. – MalsR Feb 29 '12 at 21:50