JSTL (JSP Standard Tag Library) is a JSP based standard tag library which offers tags to control the flow in the JSP page, date/number formatting and internationalization facilities and several utility EL functions.
JSTL (JSP Standard Tag Library) is a JSP based standard tag library which offers <c:xxx> tags to control the flow in the JSP page, <fmt:xxx> tags for date/number formatting and internationalization facilities and several ${fn:xxx()} utility EL functions.
JSTL (JSP Standard Tag Library) is a JSP based standard tag library which offers <c:xxx> tags to control the flow in the JSP page, <fmt:xxx> tags for date/number formatting and internationalization facilities and several ${fn:xxx()} utility EL functions.
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
Include file (Java)
<%@ include file="/WEB-INF/jsp/common/date.jsp" %>
Include file (JSP)
<jsp:include page="/WEB-INF/jsp/common/date.jsp">
<jsp:param name="title" value="Date and Time"/>
</jsp:include>
Import a URL
<c:import url="http://www.google.com">
<jsp:param name="title" value="Google"/>
</c:import>
Set a variable to be used within the page
<c:set var="title" value="Web Developmenent Blog"/>
This can be used inside the jsp page by calling ${title}
For each loop
<c:forEach items="${result}" varStatus="status" var="item">
${item.title}
</c:forEach>
For each loop with a pre-determined limit
Display the first 3 items
<c:forEach items="${result}" varStatus="status"
var="item" begin="0" end="2">
...
</c:forEach>
Check if it is the last item in the loop
<c:forEach items="${items}" var="item" varStatus="status">
${item}<c:if test="${not status.last}">, </c:if>
</c:forEach>
If condition
<c:if test="${not empty title}">
Title isn't empty
</c:if>
If condition with more than one possible result
<c:choose>
<c:when test="${linkNameLen > 18}">
<c:set var='linkNameShort' value='${fn:substring(link.linkName, 0, 18)}...'/>
</c:when>
<c:otherwise>
<c:set var='linkNameShort' value='${link.linkName}'/>
</c:otherwise>
</c:choose>
Display a subset of a string
Display only the first 80 characters
${fn:substring(url, 0, 80)}
Count the total number of characters in a string
<c:if test="${fn:length(url) > 80}">...</c:if>
Replace certain characters in a string
<c:set var="description"
value="${fn:replace(string, 'Old Text', 'New Text')}" />
Convert string to all lowercases
${fn:toLowerCase(string)}
Check if a string contains certain value
<c:if test="${not empty param.gender &&
fn:contains(param.gender,'Female')}"> checked="checked"</c:if>
Split a string into an array
Eg: Split 14/10/2009
<c:set var="date" value="${fn:split(start_date, '/')}" />
<c:set var="day" value="${date[0]}" />
<c:set var="month" value="${date[1]}" />
<c:set var="year" value="${date[2]}" />
Check if a string starts with certain characters
<c:choose>
<c:when test="${fn:startsWith(website,'http') }">
<a href="${website}">${website}</a>
</c:when>
<c:otherwise>
<a href="http://${website}">http://${website}</a>
</c:otherwise>
</c:choose>
Display text with html values escaped
<c:out value="${summary}"/>
Display text with html values
<c:out value="${cat.name}" escapeXml="false"/>
Escape html values (same result as using <c:out>)
${fn:escapeXml(summary)}
OR operator
<c:if test="${(title == 'null') || (empty title)}">
...
</c:if>
AND operator
<c:if test="${(title != 'null') && (title == 'Page 1')}">
...
</c:if>
Maths operators
Addition
<c:if test="${counter + 2 == 4}">
Subtraction
<c:if test="${counter - 2 == 0}">
Multiplication
<c:if test="${counter * 2 == 4}">
Division
<c:if test="${counter / 2 == 4}">
Remainder
<c:if test="${counter % 2 == 0}">
Form a URL with parameters
<c:url value="http://www.google.com/search" var="google_search">
<c:param name="q" value="web development blog"/>
<c:param name="hl" value="en"/>
</c:url>
<c:out value="${google_search}"/>
Check a parameter from URL
<c:if test="${param.name != 'null' && not empty param.name}">
...
</c:if>
Check session
<c:when test="${not empty sessionScope['javax.portlet.userinfo']}">
Check if form is submitted
<c:if test="${pageContext.request.method == 'POST'}">
...
</c:if>
The <c:out> tag is probably the most commonly used (and sometimes the most misunderstood) tag in the Core tag library. Its purpose is to assist in the outputting of content to your JSPs. You might immediately wonder how this is different from simply using an EL expression to output content. Perhaps more confusing is that is almost always used with one or more EL expressions!
<c:out value="${someVariable}" />
<c:out> does more than simply outputting the text. It escapes the HTML special chars. Use it (or ${fn:escapeXml()}) every time you're not absolutely sure that the text doesn't contain any of these characters: ", ', <, >, &. Else, you'll have invalid HTML (in the best case), a broken page, or cross-site scripting attacks (in the worst case).
I'll give you a simple example so that you understand. If you develop a forum, and someone posts the following message, and you don't use <c:out> to display this message, you'll have a problem:
<script>while (true) alert("you're a loser");</script>
The tag properly encodes URLs, and rewrites them if necessary to add the session ID, and can also output URLs in your JSP.
The tag accomplishes this behavior together with the <c:param> tag, which specifies query parameters to include in the URL. If the URL is a relative URL, the tag prepends the URL with the context path for your application so that the browser receives the correct absolute URL. Consider:
<c:url value="http://www.example.net/content/news/today.html" />
Because this URL is an absolute URL and contains no spaces or other special characters to encode, it is not changed in any way. Using the
tag for such a purpose is really pointless. However, if you had query parameters that you need to include in the URL, that would be a different story.
<c:url value="http://www.example.net/content/news/today.jsp">
<c:param name="story" value="${storyId}" />
<c:param name="seo" value="${seoString}" />
</c:url>
In this case the <c:url> tag will properly form and encode the query string. The story parameter might not be a problem, but the seo parameter (likely a search engine optimization string) could contain spaces, question marks, ampersands, and other special characters, all of which are encoded to ensure that they do not corrupt the URL. Where the <c:url> tag is probably most helpful, however, is in the encoding of relative URLs.
Consider that your application is deployed to http://www.example.org/forums/ and you place the following link tag in your HTML:
<a href="/view.jsp?forumId=12">Product Forum</a>
When a user clicked that link, they would be taken to http://www.example.org/view .jsp?forumId=12. You probably meant for that URL to be relative to the forum application, not the entire website. You could easily change your link to point to /forums/view.jsp?forumId=12, but what if you write a forums application that anyone can download and use on their website. You don’t know whether they’re going to deploy the application to /forums, /discussion, /boards, or even just /. This is where the
tag shines.
<a href="<c:url value="/view.jsp">
<c:param name="forumId" value="12" />
</c:url>">Product Forum</a>
This tag is a particularly interesting action that enables the retrieval of the contents of the resource at a particular URL. Those contents can then be inlined to the response, saved to a String variable, or saved to a Reader variable.
Tag Library Descriptor (TLD), a special file that describes the tags and/or functions in a library. In this chapter you learn more about the TLD and how tags and functions are declared within them. You also learn how to create tag handlers and tag files.
All JSP tags result in execution of some tag handler. The tag handler is an implementation of javax .servlet.jsp.tagext.Tag or javax.servlet.jsp.tagext.SimpleTag and contains the Java code necessary to achieve the tag’s wanted behavior. A tag handler is specified within a tag definition in a TLD, and the container uses this information to map a tag in a JSP to the Java code that should execute in place of that tag.
However, tags do not always have to be written as Java classes explicitly. Just like the container can translate and compile JSPs into HttpServlets, it can also translate and compile tag files into SimpleTags. Tag files are not as powerful as straight Java code, and you cannot do things like parse nested tags within a tag file like you can with an explicit tag handler, but tag files do have the advantages of using simple markup like JSPs and allowing the use of other JSP tags within them. A tag definition in a TLD can point to either a tag handler class or to a tag file. However, you do not have to create a TLD to use a tag defined in a tag file. The taglib directive enables you to do this using the tagdir attribute:
<%@ taglib prefix="myTags" tagdir="/WEB-INF/tags" %>
Notice how this taglib directive is different from others you have seen. Instead of specifying a URI for a TLD file containing the tag library’s definitions, it specifies a directory in which tag files can be found. Any .tag or .tagx files within the tagdir directory are bound to the myTags namespace in this case. Tag files in an application must be within the /WEB-INF/tags directory, but they may also be within a subdirectory of this directory. You could use this to have multiple name spaces of tag files in your application, as in the following example.
<%@ taglib prefix="t" tagdir="/WEB-INF/tags/template" %>
<%@ taglib prefix="f" tagdir="/WEB-INF/tags/formats" %>
JSP tag files can also be defined in JAR files within your application’s /WEB-INF/lib directory, but the rules are slightly different. Whereas tag files in your application must be in /WEB-INF/tags and can be declared either in a TLD or with a taglib directive pointing to the directory, tag files in a JAR file are placed in the /META-INF/tags directory and mu
The custom tags can be implemented or redistributed with tag handlers that are written in Java. These redistributable tags must be in a library called Tag Library Descriptor. The TLD file is an XML file. It contains the information about the tag library and about detailed description in the library. TLDs are handled by the container and also by the development tools of JSP that is to validate the tags.
The extension for the tag library file is .tld and must be packaged in the WEB-INF/ directory or in the /META-INF directory or subdirectory of the tag library packaged in a JAR file or subdirectory of the WAR file. The tag library will be automatically generated by the web container if the file is packaged in /WEB-INF/tags or in a subdirectory.
A tag library file must begin with a root element ‘taglib’ which specifies the schema and the JSP version. For Example:
<?xml version="1.0" encoding="UTF-8" ?>
<!--...Copyright (c) 2010 Oracle and/or its affiliates. All rights reserved...-->
<taglib xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd"
version="2.1">
...
</taglib>
If you are at all familiar with XML, you know that this just sets up the document root element and declares that the document is using the XML schema definition web-jsptaglibrary_2_1.xsd. This XML schema defines how a TLD is structured, just like web-app_3_1.xsd in web.xml defines how the deployment descriptor is structured. The only thing of importance about the JSP tag library XSD that is not obvious from reading through a TLD file is that the schema uses a strict element sequence, meaning that any elements you use must come in a certain order, or your TLD file will not validate. The first five elements within the document root declare general information about the tag library.
<description>JSTL 1.2 core library</description>
<display-name>JSTL core</display-name>
<tlib-version>1.2</tlib-version>
<short-name>c</short-name>
<uri>http://java.sun.com/jsp/jstl/core</uri>
The <tag> element is the workhorse of the TLD and is responsible for defining tags in your tag library.
<tag>
<description>
Catches any Throwable that occurs in its body and optionally
exposes it.
</description>
<name>catch</name>
<tag-class>org.apache.taglibs.standard.tag.common.core.CatchTag</tag-class>
<body-content>JSP</body-content>
<attribute>
<description>
exception thrown from a nested action. The type of the
scoped variable is the type of the exception thrown.
</description>
<name>var</name>
<required>false</required>
<rtexprvalue>false</rtexprvalue>
</attribute>
</tag>
You have already seen how you can use the taglib directive to collect a directory of tag files into a namespace of custom tags, and you now know that tag files are essentially JSPs with slightly different semantics. You learn the details of these semantics later in this section. However, you should also know how to define tag files within a Tag Library Descriptor. Remember that tag files shipped inside of JAR libraries must be defined inside a TLD. Also, if you have one or more tag files that you would like to group with one or more tag handlers or JSP functions into the same namespace, you need to define those tag files within the TLD even if they are not shipped inside of JAR libraries.
You will not find an example of <tag-file> within the JSTL TLDs, but the following XML demonstrates its basic use
<tag-file>
<description>This tag outputs bar.</description>
<name>foo</name>
<path>/WEB-INF/tags/foo.tag</path>
</tag-file>