It's a way to include reusable code, that adds some of the flexibility of a tag handler. The code to include must be in a source with the *.tag extension.
This is an example for writing a letter, using a custom tag:
index.jsp:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib prefix="message" tagdir="/WEB-INF/tags" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Title here</title> </head> <body> <message:email dest="Arthur" author="mike"> I'm writing to you because.... </message:email> </body> </html>
WEB-INF/tags/email.tag:
<%@ tag language="java" pageEncoding="ISO-8859-1"%> <%@ attribute name="dest" required="true" rtexprvalue="true" %> <%@ attribute name="author" required="true" rtexprvalue="true" %> <%@ tag body-content="scriptless" %> Dear ${dest}, <br/> <jsp:doBody/> <br/> Bye<br/> ${author}<br/>
There are other two ways to include reusable code.
The first is by using the tag <jsp:include>. This is an example:
index.jsp:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Title here</title> </head> <body> <jsp:include page="header.jsp"> <jsp:param value="This is an header with a title" name="title"/> </jsp:include> </body> </html>
header.jsp:
<h1>${param.title}</h1>
The second way is by using the directive <%@ include>. This is an example:
index.jsp:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib prefix="message" tagdir="/WEB-INF/tags" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Title here</title> </head> <body> <%@ include file="header.jsp" %> </body> </html>
header.jsp:
<h1>This is an header</h1>
The difference between the two is that the directive is used at translation time, whereas the JSP action is executed at request time.
So if you just need a static include, then use the directive.
If you need a dynamic include and you need to pass parameters, then use the JSP action.
If you need something more sophisticated and similar to a custom tag, then use a tag file.
Copyright © 2013 Welcome to the website of Davis Fiore. All Rights Reserved.