JSTL

JSTL - Java Server Pages Standard Tag Library

  • JSTL stands for JSP Standard Tag Library
  • JSTL is collection of utility tags can be used by developers in JSP
  • JSTL is implemented by SUN

JSTL Types

  • Core tags
  • Formatting tags
  • SQL tags
  • XML tags

JSTL Core Tags

<c:out>

  • It is used to display data to JSP output stream
  • attributes: value
  • Usage:
    • <c:out value=”Atul” />
    • <c:out value=”${msg}” />

<c:set>

  • It is used to set the attribute in the required scope
  • attributes: var, value, scope
  • Usage:
    • <c:set var=”name” value=”Atul” scope=”session” />
    • Equivalent to: session.setAttribute(name, “Atul”);

<c:remove>

  • It is used to remove the attributes from the required scope
  • attributes: var, scope
  • Usage:
    • <c:remove var=”name” scope=”session” />
  • Equivalent to session.removeAttribute(“name”);

<c:if>

  • It is used to perform conditional checks
  • attributes: test
  • Usage:
    • <cif test=”${name eq “Atul”}”>You are Atul</c:if>

<c:choose> <c:when> and <c:otherwise>

  • These are used to perform conditional checks like switch case statements
  • attributes:
    • choose: no attribute available
    • when: test
    • otherwise: no attribute available
  • Usage:

<c:choose>

<c:when test="${id eq 101}">

id is 101

</c:when>

<c:when test="${id eq 102}">

id is 102

</c:when>

<c:otherwise>

id is not available

</c:otherwise>

</c:choose>


<c:forEach>

  • It is used to access elements of collection or array
  • attributes: var, items, start, end, step, carStatus
  • Usage: You can access the following type of data
    • Collection of String, Wrappers and Date
    • Collection of Collections
    • Collection of custom or user defined objects
    • Map objects
    • Collection of map objects

<c:import>

  • It is used to include the resources (HTML or JSP)
  • attribute: url
  • Usage:

<jsp:include page=”header.jsp” />

<c:import url=”header.jsp” />

<c:import url=http://www.google.com />

  • <jsp:include> can include the resources which are in same server
  • <c:import> can include the resources which are in same and different server

<c:redirect>

  • It is used to redirect request to the specified resource (HTML or JSP)
  • attributes: url
  • Usage

<c:redirect url=”header.jsp” />

<c:redirect url=http://www.google.com />

  • <jsp:forward> can forward the request to resources which are in same application
  • <c:redirect> can forward request to resources which are in same and different application

<c:param>

  • It is used to define parameters
  • It must be used along with <c:import> and <c:redirect>
  • Usage:

<c:param name=”myName” value=”Atul” />

  • Examples

<c:import url=”header.jsp”>

<c:param name=”companyName” value=”My Company” />

</c:import>


<c:redirect url=”home.jsp”>

<c:param name=”companyName” value=”My Company” />

</c: redirect>


<c:url>

  • It is used to encode the url with sessionid
  • attribute: value
  • Usage:

<c:url value=”hello.jsp” />

<a href=”hello.jsp”>Click Here</a>

<a href=’<c:url value=”hello.jsp” />’>Click Here</a>

<a href=’<%= response.encodeURL(“hello.jsp”)%>’>Click Here</a>

Custom tags

  • Dynamic contents can displayed using EL expressions and JSTL tags
  • But if these tags are not enough for you application requirements then custom tags can be developed
  • These tags works similar to the JSTL tags

Tag Extension API

  • JSP custom tags can be defined by using JSP Tag extension APIs.
  • Tag extension API bundles in javax.servlet.jsp.tagext; package
  • This package contains the following classes and interfaces
    • Tag (interface)
    • IterationTag (interface)
    • BodyTag (interface)
    • TagSupport (class)
    • BodyTagSupport (class)
    • BodyContext (class)
  • Tag (I)
    • It acts as a base interface for all THCs (Tag Handler Classes)
    • Every THC should implement this interface either directly or indirectly
    • Tag interface defines following six methods

setPageContext()

setParent()

doStartTag()

doEndTag()

release()

    • Tag interface defines following four constants

EVAL_BODY_INCLUDE

SKIP_BODY

EVAL_PAGE

SKIP_PAGE

  • All methods can be applicable on any THC object
  • If we want to include tag body at most once without any manipulation then we should go for Tag interface
  • IterationTag (I)
    • It is child interface of Tag
    • If we want to include tag body multiple times without any manipulation then we should go for IterationTag interface
    • It define one extra method doAfterBody()
  • BodyTag (I)
    • It is child interface of IterationTag
    • If we want to manipulate the tag body then we should go for BodyTag interface
    • This interface defines two new methods

setBodyContent()

doInitBody()

  • TagSupport (C)
    • It implements IterationTag interface and provides default implementation for all methods and hence this class act as base class to develop Tag Handler class where TagBody can be included any no. of times without manipulation
    • This class act as a adaptor for Tag and IterationTag interfaces
  • BodyTagSupport (C)
    • This class implements BodyTag interface and provides default implementation for all its methods and it is child class of TagSupport class
    • We can use this class as a base class for implementing custom tag that can process the tag body
    • This class act as a adaptor for BodyTag interface
  • BodyContext (C)
    • BodyContext object act as a buffer for Tag body, it is the child class of JspWriter
    • We can use this BodyContext class only with in BodyTag interface and BodyTagSupport class

8.3.2 How to develop JSP Custom tags

  • Identify information related to the tag
    • name of the tag
    • body-content
    • attributes allowed for tag
  • Write tag handler class
    • Define Java class by extending TagSupport or BodyTagSupport class
    • Define variables for the attributes defined for tags
    • Define setter methods for variables
    • Override the required lifecycle methods
  • Write .tld file using above information and place it under WEB-INF or any subdirectory
    • Specify tag information in the tld file which includes
    • URI
    • name of the tag
    • body content
    • tag-class
    • attributes allowed for the tag

8.3.3 How to use JSP Custom tags

  • taglib directives are used to use custom tags
  • Specify uri and prefix attributes values in taglib directive
  • URI of taglib directive must match with URI specified in TLD file
  • Prefix of taglib directive can be any user specified values
  • <%@ taglib prefix="g" uri="http://atuldwivedi.com/ctag"%>
  • Example

We will see an example which demonstrate the how to develop and use JSP Custom Tags. Requirement is to develop a customer tag to greet the user and if no user is specified then communicate the same to the user. To develop custom tag for above mentioned requirement we need one TLD file to specify all tag related information, one Tag handler Java class to handle lifecycle of custom tag and to perform logic on that and finally one JSP file as a starting point of this i.e. from where request can be initiated for custom tag.

TLD file

<taglib>
  <tlib-version>1.0</tlib-version>
 <jsp-version>1.2</jsp-version>
 <uri>http://atuldwivedi.com/ctag</uri>
 <tag>
  <name>greet</name>
  <tag-class>com.atuldwivedi.learnjsp.customtag.GreetTagHandler
  </tag-class>
  <body-content>empty</body-content>
  <attribute>
   <name>uname</name>
   <required>true</required>
   <rtexprvalue>true</rtexprvalue>
  </attribute>
 </tag>
</taglib>

Tag Handler Class

package com.atuldwivedi.learnjsp.customtag;

import java.io.IOException;
import java.io.Writer;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

public class GreetTagHandler extends TagSupport {

  private static final long serialVersionUID = 1L;
 private String uname;

 public void setUname(String uname) {
  this.uname = uname;
 }

 @Override
 public int doEndTag() throws JspException {
  Writer out = pageContext.getOut();
  try {
   if (uname == null || uname.trim().isEmpty()) {
    out.write("You have not specified your name.");
   } else {
    out.write("Hello " + uname);
   }
  } catch (IOException e) {
   e.printStackTrace();
  }
  return super.doEndTag();
 }
}

JSP Custom Tag processing flow

  • Whenever any custom tag is encountered in the JSP file then container
  • takes prefix and name of the tag
  • checks any taglib directive available whose prefix is matching
  • If no taglib directive is available then that tag will be ignored
  • If matching taglib directive is available then uri from matching taglib directive will be taken
  • checks whether any TLD file is available whose URI is matching with URI of taglib directive identified
  • If matching TLD file found then container
    • checks whether tag name is found in that TLD or not
    • if tag name is not found then
      • No tag “greet” defined in tag library imported with prefix “g”
    • if tag name is found, container checks whether attributes are used correctly
    • if attributes names are not used correctly then
      • Undefined attribute name “uname”
      • Missing required attribute “uname”
    • if attributes are used properly then tag handler class will be taken
  • Container starts tag handler class lifecycle
  • Tag handler class processes the custom tags
  • Once tag handler class lifecycle is completed then tag processing is completed

8.3.5 Extending TagSupport

  • Custom tags can be developed with and without body by extending TagSupport class
  • Using TagSupport all types of tags like simple, nested, tags with and without body, looping tags can be developed

8.3.6 Extending BodyTagSupport

  • BodyTagSupport should be extended when body content is required to be modified
  • It provide two extra lifecyle method as compare to TagSupport

public void setBodyContent(BodyContent bodyContent)

public void doInitBody()

  • You need to return following value from doStartTag() to execute setBodyContent()

EVAL_BODY_BUFFERED

  • This is the default from deStartSTag() in case of BodyTagSupport class
  • You can use the below method to get the body content in the tag handler class

public BodyContent getBodyContent()