Writing a traditional custom tag requires two steps:
Writing and compiling a tag handler.
Defining the tag that is associated with the tag handler.
To work, tag files must be placed in the WEB-INF/tags directory under your application directory OR a subdirectory under it. The container converts each tag file found in (or uder) WEB-INF/tags into a tag handler.
A number of implicit objects are available from inside of a tag file. You can access these objects from a script or an EL expression:
Table 10.2. The Tag Files implicit objects
| Object | Type |
|---|---|
| request | javax.servlet.http.HttpServletRequest |
| response | javax.servlet.http.HttpServletResponse |
| out | javax.servlet.jsp.JspWriter |
| session | javax.servlet.http.HttpSession |
| application | javax.servlet.ServletContext |
| config | javax.servlet.ServletConfig |
| jspContext | javax.servlet.jsp.JspContext |
This is the example of a tag library in which the tag file simply writes a String to the implicit out object:
<%— WEB-INF/tags/myExample.tld —%>
<%
out.println("Hello, World !");
%>
In JSP you need the taglib directive as usual, with the
prefix attribute to identify your tag library throughout the page.
NOTE, instead of a uri attribute, you have a tagdir
attribute. The tagdir attribute refers to the
WEB-INF/tags directory OR ANY subdirectory below
WEB-INF/tags:
<%@ taglib prefix="simpleTag" tagdir="/WEB-INF/tags" %> <simpleTag:myExample />
Combined with the expression language (EL), you can really build a scriptless JSP page very rapidly. The following example accepts an attribute from a calling JSP page and converts it to the upper case:
<%— WEB-INF/tags/myExample2.tld —%> <%@ attribute name="someAttribute" %> <% someAttribute = someAttribute.toUpperCase(); out.println(someAttribute); %>The following JSP page that uses the tag file:
<%@ taglib prefix="simpleTag" tagdir="/WEB-INF/tags" %> <simpleTag:myExample2 someAttribute="hello" />
example, which is Java-code-free:
<%— WEB-INF/tags/myExample3.tag —%>
<%@ variable name-given="myVar" scope="AT_BEGIN" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="myVar" value="3"/>
After: ${myVar}
<jsp:doBody/>
To use the tag file, use the following JSP page:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="sampleTag" tagdir="/WEB-INF/tags" %>
<c:set var="myVar" value="1"/>
Before: ${myVar} <br>
<simpleTag:myExample3/>
|
|
Hosting provided by PerfoHost: KVM VPS. Unix VPS. Windows VPS. VPN. Domains. Dedicated servers. Colocation.