Creating Custom JSP Tag Libraries: The Basicscourses.coreservlets.com/Course-Materials/.../07-Basic-Custom-Tags.pdf · Creating Custom JSP Tag Libraries: The Basics 2 ... – Components
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Customized Java EE Training: http://courses.coreservlets.com/Java, JSF 2, PrimeFaces, Servlets, JSP, Ajax, jQuery, Spring, Hibernate, RESTful Web Services, Hadoop, Android.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Java-Based Tags
8
Components That Make Up a Tag Library
• The Tag Handler Class– Java code that says what to output– Must implement javax.servlet.jsp.tagext.SimpleTag – Usually extends SimpleTagSupport– Goes in same directories as servlet class files and beans
• The Tag Library Descriptor File– XML file describing tag name, attributes, and
implementing tag handler class– Goes under WEB-INF
• The JSP File– Imports a tag library (referencing URL of descriptor file)– Defines tag prefix– Uses tags9
Defining a Simple Tag Handler Class
• Extend the SimpleTagSupport class• Import needed packages
public class SimplePrimeTag extends SimpleTagSupport {protected int length = 50;
public void doTag() throws JspException, IOException {JspWriter out = getJspContext().getOut();BigInteger prime = Primes.nextPrime(Primes.random(length));
out.print(prime);}
}11
Defining a Simple Tag Library Descriptor
• Start with XML header• Top-level element is taglib
– Just use tlib-version and short-name as in example• Each tag defined by tag element with:
– description, which gives short info. Optional.– name, which defines the base tag name. – tag-class, which gives the fully qualified class name of
the tag handler. – body-content, which specifies if tag is standalone or
contains content between start and end tag. • You can have multiple tag entries in each TLD file• Put TLD file somewhere under WEB-INF
• Don’t memorize XML header and standard part; download and modify online version– The important thing is to know how to write tag entries– Place TLD file somewhere under WEB-INF13
Accessing Custom Tags From JSP Files
• Import the tag library– Specify location of TLD file
• The tag element must contain a nested attribute element
• The attribute element has three further-nested elements– name, a required element that defines the case-sensitive
attribute name. – required, a required element that stipulates whether the
attribute must always be supplied (true) or is optional (false).
– rtexprvalue, an optional attribute that indicates whether the attribute value can be a JSP expression like <%= expression %> (true) or whether it must be a fixed string (false). The default value is false.
20
TLD File for PrimeTag
...<taglib ...>
...<tag>
<description>Outputs an N-digit prime</description><name>prime</name><tag-class>coreservlets.tags.PrimeTag</tag-class><body-content>empty</body-content><attribute>
// Output content of the bodygetJspBody().invoke(null);out.println("</SPAN></TH></TR></TABLE>" +
"<BR CLEAR=\"ALL\"><BR>");}
}
27
Using Tag Body:The Tag Library Descriptor File
• Only difference is body-content element– Should be scriptless instead of empty:<tag><name>…</name><tag-class>…</tag-class><body-content>scriptless</body-content>
</tag>
• Legal values for body-content– empty: no body content
• Body content is ignored even if supplied– scriptless: body content is included
• Can contain plain text, EL elements, other custom tags, and page directives
• No explicit scripting allowed (<%= ... %>)– tagdependent: body content is processed by tag
Customized Java EE Training: http://courses.coreservlets.com/Java, JSF 2, PrimeFaces, Servlets, JSP, Ajax, jQuery, Spring, Hibernate, RESTful Web Services, Hadoop, Android.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
JSP-Based Tags(Tag Files)
40
Tag Files: Custom Tags Using JSP Syntax
• Two Approaches– When there is lots of logic, use Java to create output
• Analagous to when you use servlets
– When there is lots of formatting, use JSP to create output• Analagous to when you use JSP pages
• Pros– Very good for complex text formatting– Very concise
• Cons– Not good for complicated logic– Runs only in JSP 2.0 and later
• Java-based versions had “classic” syntax that worked in older servers (e.g., BEA WebLogic 8.1, Oracle 9i AS)
41
Simple Standalone Tags
• Java-based approach requires three pieces– Java code that overrides doTag to generate output
• Strengths and weaknesses generally similar to those of servlets, but more cumbersome
– Tag Library Descriptor (TLD) file that maps Java class name to tag name
– JSP page that refers to specific location of TLD file
• JSP-based approach requires two pieces– JSP code (tag file) that shows result
• /WEB-INF/tags/someName.tag
– No TLD file: tag name taken from tag-file name– JSP page that refers to directory containing tag file
• /WEB-INF/tags or a subdirectory thereof42
Tag Files
• Look just like regular JSP files, except– Must be located in (or under) WEB-INF/tags– Must be named blah.tag, not blah.jsp– You use <%@ tag ... %> instead of <%@ page ... %>– You use predefined variable jspContext instead of pageContext
• But you can cast it to PageContext• Other variables (request, response, etc.) are the same
• Example
WEB-INF/tags/date.tag
<%@ tag import="java.util.*" %>Date is <%= new Date() %>
public class SimplePrimeTag extends SimpleTagSupport {protected int length = 50;
public void doTag() throws JspException, IOException {JspWriter out = getJspContext().getOut();BigInteger prime = Primes.nextPrime(Primes.random(length));
<description>Outputs an N-digit prime</description><name>prime</name><tag-class>coreservlets.tags.PrimeTag</tag-class><body-content>empty</body-content><attribute>
<name>length</name><required>false</required>
</attribute></tag>
…
53
Java-Based Tags: Usage in JSP(Tag with Attributes)…<BODY><H1>Some N-Digit Primes</H1><%@ taglib uri="/WEB-INF/tlds/csajsp-taglib.tld"
• Java-based tags– Change body-content from empty to scriptless (in TLD)– Call getJspBody().invoke(null)– Still need setter method and TLD entry for every attribute
• JSP-based tags (tag files)– Use <jsp:doBody/> to output tag body– No major syntax changes– Access to attributes still much simpler
59
Java-Based Tags: Code (Tag with Body)
public class HeadingTag extends SimpleTagSupport {private String align;private String bgColor;private String border;private String fgColor;private String font;private String size;
public void setAlign(String align) {this.align = align;
}
public void setBgColor(String bgColor) {this.bgColor = bgColor;
}
public void setBorder(String border) {this.border = border;
}…
60
Java-Based Tags: Code (Tag with Body -- Continued)
public void doTag() throws JspException, IOException {JspWriter out = getJspContext().getOut();out.print("<TABLE ALIGN=\"" + align + "\"\n" +
• Listing of other open-source tag libraries– http://java-source.net/open-source/jsp-tag-libraries
• Google queries and searching• Google maps wrappers• Menus• Paging of large data sets• Fancy UIs
69
Summary: Java-Based Tags
• Tag handler class– Extend SimpleTagSupport– Override doTag– Get the JspWriter with getJspContext().getOut()– Use the JspWriter to generate output– Output tag body with getJspBody().invoke(null);– Define setBlah for each attribute named blah
– <blah:tagName/> or <blah:tagName>...</blah:tagName>70
Summary: Tag Files
• Tag File– /WEB-INF/tags/tagName.tag– Create chunk of JSP that generates the output– Declare attributes with <%@ attribute ...%>– Output attributes with ${attributeName}– Output the tag body with <jsp:doBody/>– Refactor Java code so methods take strings as args
• JSP File– <%@ taglib tagdir="/WEB-INF/tags prefix="blah" %>– <blah:tagName/> or