The following is a simple example for creating a custom tag library (taglib) for the Apache Tomcat JSP server and could be used as a simple template engine.
-
Create a taglib definition file in “WEB-INF/jsp/mytaglib.tld”.
<taglib> <tlib-version>1.0</tlib-version> <jsp-version>1.2</jsp-version> <short-name>example tags</short-name> <uri>http://www.peterfinch.me/mytag</uri> <tag> <name>menu</name> <tag-class>me.peterfinch.MenuTag</tag-class> </tag> <tag> <name>master</name> <tag-class>me.peterfinch.MasterTag</tag-class> </tag> </taglib>
-
Add taglib section to web.xml
<web-app> ... <jsp-config> <taglib> <taglib-uri>http://www.peterfinch.me/mytag</taglib-uri> <taglib-location>/WEB-INF/jsp/mytaglib.tld</taglib-location> </taglib> </jsp-config> </web-app>
-
Create MasterTag Java class to handle the tag events. This class wraps the encoded HTML (generated by the JSP) and could be used as a simple page template.
package me.peterfinch; import java.io.IOException; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.tagext.BodyContent; import javax.servlet.jsp.tagext.BodyTagSupport; public class MasterTag extends BodyTagSupport { @Override public int doAfterBody() throws JspException { try { BodyContent bodycontent = getBodyContent(); String body = bodycontent.getString(); JspWriter out = bodyContent.getEnclosingWriter(); out.print("<div class='master' style='border:1px solid black'>") ; out.print(body) ; out.print("</div>") ; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return SKIP_BODY; } }
-
Add MenuTag Java class handler. This just replaces the tag, and it’s contents with some predefined HTML and could be used as a Menu (or anything else you desire)
package me.peterfinch; import java.io.IOException; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.tagext.BodyTagSupport; public class MenuTag extends BodyTagSupport { @Override public int doAfterBody() throws JspException { try { String i = this.pageContext.getRequest().getParameter("i") ; JspWriter out = bodyContent.getEnclosingWriter(); out.print("<a href='index.jsp'>Home</a> " + i) ; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return SKIP_BODY; } }
-
Add taglib definition to JSP page
<%@ taglib uri="http://www.peterfinch.me/mytag" prefix="my" %>
-
Add the custom tags to to your page
<my:master> <my:menu></my:menu> <h1>Hello from index.jsp</h1> </my:master>
Advertisements