Introduction
In this post, I will introduce how to achieve html layout by jsp.You just define layout and put piece of elements in each actual jsp.
I won't explain details but just show you an quick example for sharing "header & footer" in all jsp pages.
If you are interested in how & why it works, please refer jsp documentation (or googling).
Code
Simply you need to prepare a layout tag file and actual jsp files.- Prepare layout.tag (actually name is not so important) and put it under WEB-INF/tags.
- Put header.jsp and footer.jsp under WEB-INF/views/
- Create actual jsp which include taglib you previously defined above step.
Ok now I will show you the actual codes.
layout.tag
A key part is using fragment feature.<%@tag description="Layout template" pageEncoding="UTF-8"%> <%@attribute name="main" fragment="true" %> <%@attribute name="head" fragment="true" %> <%@attribute name="lang" %> <!DOCTYPE html> <html lang="${lang}"> <head> <%-- shared resources used in your web application --%> <link type="text/css" rel="stylesheet" href="/css/sample.css"> <jsp:invoke fragment="head"/> </head> <body> <jsp:include page="../views/header.jsp" flush="true" /> <div id="main"> <jsp:invoke fragment="main"/> </div> <jsp:include page="../views/footer.jsp" flush="true" /> </body> </html>
jsp using layout.tag
Just write actual html (or jsp) code inside attribute tag with corresponding name.<%@ page trimDirectiveWhitespaces="true" %> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%-- add taglib directory where layout.tag is defined --%> <%@ taglib prefix="t" tagdir="/WEB-INF/tags" %> <t:layout lang="en"> <jsp:attribute name="head"> <meta name="description" content="Duke Software"> <title>Duke's Music Artists Database</title> </jsp:attribute> <jsp:attribute name="main"> <h1>Welcome to Duke Software</h1> </jsp:attribute> </t:layout>
Note
I think the method is very simple...Maybe next step is customizing (override) header or footer in specific page. (I haven't found cleaner solution in pure jsp yet.).
However rather than spending time by screwing around jsp, maybe better to use existing template engine.
If you have experience for PHP, you know a lot about more powerful template engine like Twig.
Also maybe you should use template engine for Java like Velocity, FreeMarker, or StringTemplate.
コメント