Overview of JSTL Tags

This section gives you an overview of JSTL tags. This section will introduce you with all the tags provided by the JSTL library.

Overview of JSTL Tags

Overview of JSTL Tags

     

This section gives you an overview of JSTL tags. This section will introduce you with all the tags provided by the JSTL library.

The JSTL 1.1 API Specification consists of following packages:

Tag Description
Core (javax.servlet.jsp.jstl.core) General purpose actions
Format (javax.servlet.jsp.jstl.fmt) Internationalization and Localization
SQL (javax.servlet.jsp.jstl.sql) Common database tasks
Tag Library Validator(javax.servlet.jsp.jstl.tlv) Tag Library Validators

You can view the api online at http://java.sun.com/products/jsp/jstl/1.1/docs/api/index.html.

Description of JSTL Tags

Core Tags: 

These tags provides the core functionality that a programming language is supposed to provide, such as codition, iteration etc.

1). <c:out>

This tag is used to evaluate an expression and output the result to the current JspWriter object.

Syntax:

<c:out value="value" [escapeXml="{true|false}"]
  [default="defaultValue"] />

 

2). <c:forEach>

This tag provide functionality to iterate over an array or collection without using java code.

Syntax:

<c:forEach [var="varName"] items = "collection"
   [varStatus="varStatusName"]
   [begin="start"] [end="end"] [step="step"]>

  
.... body..
</c:forEach>

3.) <c:if>

This is used for conditional branching within the jsp page based on some test.

Syntax:

<c:if  test ="testCondition"
  var="varName" [scope="{page|request|session|application}"] />

4). <c:set>

This tag is used to set attributes within specified scopes in jsp pages

Syntax:

<c:set value="val"
  var="varname" [scope="{page|request|session|application}"] />

5).  <c:remove>

This tag is used to remove a scoped variable.

Syntax

<c:remove var="varName"
  [scope="{page|request|session|application}"] />

6).  <c:url>

This tag is used for session management and URL rewriting.

Syntax:

<c:url value="value" [context="context"]
  [var="varName"] [scope="{page|request|session|application}"] />

7).  <c:import>

This is used to include external resources inside the jsp page.

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

These tags are used for conditional branching, that is provided by switch.... case statement in most programming languages.
<c:choose> is used for mutually exclusive conditional execution.

Syntax:

<c:choose>
   ..body..... (<when> and <otherwise> subtags)
</c:choose>

<c:when> represents an alternative within a <c:choose> action.

Syntax:

<c:when test="testCondition">
  .... body
</c:when>

<c:otherwise> represents the last alternative within a <c:choose> action.

Syntax:

<c:otherwise>
  ..... conditional block..
</c:otherwise>

8).  <c:catch>

This tag provide a try...catch like mechanism inside jsp pages without using scriptlets.

Syntax:

<c:catch [var="varName"]>
   .... nested actions
</c:catch>

9).  <c:redirect>

This provides same functionality as the sendRedirect() method of HttpServletRequest interface. It is used to redirect control to other pages within the web application.

Syntax:

<c:redirect url="value" [context="context"] />

10).  <c:param>

This tag is used to add request parameters to a URL. It is also used as a nested tag, within the <c:import>, <c:url> and <c:rediret> tags.

Syntax:

<:param name = parameterName" value = "parameterValue" />

11).  <c:forEachToken>

This tag when provided with delimiters can be used to iterate over tokens. Its functionality is like that of StringTokenizer.

Syntax:

<c:forTokens items = "tokenString" delims="delimiter"
  [var="variableName"]
  [varStatus="variableStatusName"]
  [begin="start"  [end="end"]  [step="step"]>
  ........ body content..
</c:forTokens>

Formatting Tags

The formatting tags are used for internationalization and localization of the jsp pages. Internationalization provides support for various languages and data formats. By localization web applications becomes capable of supporting specific regions or locale.

1).   <fmt:message>

This tag is used to output locale sensitive strings. The param subtag along with message provides an argument to the compound message in parent message tag. One param tag must be specified for each variable in the compound message or pattern. Replacement takes place in order of the param tags.

Syntax:

<fmt:message key = "messageKey"
   [bundle="resourceBundle"]
   [var="varName"]
   [scope="{page|request|session|application}"] />

2).  <fmt:setLocale>

This tag is used to set the default locale within a specific JSP scope. 

<fmt:setLocale value = "en_US" />

3).  <fmt:bundle>

This tag is used to create an i18n localization context to be used by its body content.

Syntax:

<fmt:bundle basename = "basename="basename"
   [prefix="prefix"]>
   body content
</fmt:bundle>

 

It creates an i18n localization context and loads its resource bundle into that context. The name of the resource bundle is specified with the basename attribute.

4).   <fmt:setBundle>

This tag creates an i18n localization context and loads its resource bundle into that context. The name of the resource bundle is specified with the basename attribute.

Syntax:

<fmt:setBundle basename = "basename"
   [var="varname"]
   [scope="{page|request|session|application}"]/>

5).   <fmt:param>

This tag is used for parametric replacement to <fmt:message> tag.

Syntax:

<fmt:param value="messageParameter"/>   

6).  <fmt:requestEncoding>

This tag is used to set the request's character encoding

Syntax:

<fmt:requestEncoding [value="charsetName"]/>

7).   <fmt:timeZone>

This tag is used to specify the time zone in which time information is to be formatted or parsed in its body content.

Syntax:

<fmt:timeZone value="timeZone">
  body content
</fmt:timeZone>

8).   <fmt:setTimeZone>

This tag is used to store specified time zone in a scoped variable or the time zone configuration variable.

Syntax:

<fmt:setTimeZone value="timeZone"
   [var="varName"]
   [scope="{page|request|session|application}"] />

9).   <fmt:formatNumber>

This tag is used to format a numeric value in a locale-sensitive or customized manner as a number, currency etc.

Syntax:

<fmt:formatNumber value = "numericValue"
    [type="{number|currency|percent}"]
    [pattern="customPattern"]
    [currencyCode="currencyCode"]
    [currencySymbol="currencySymbol"]
    [goupingUsed="{true|false}"]
    [scope="{page|request|session|application}"] />

10).   <fmt:parseNumber>

This tag is used to parse the string representation of numbers, currencies, and percentages that were formatted in a locale-sensitive or customized manner.

Syntax:

<fmt:parseNumber value="numericValue"
  [type="{number|currency|percent}"]
  [pattern="customPattern"]
  [parseLocale="parseLocale"]
  [integerOnly="{true|false}"]
  [var="varName"]
  [scope="{page|request|session|application}"]/>

11).   <fmt:formatDate>

This tag is used to format date and time according to the locale.

Syntax:

<fmt:formatDate value="date"
   [type="{time|date|both}"]
   [dateStyle="{default|short|medium|long|full}"]
   [timeStyle="{default|short|medium|long|full}"]
   [pattern="customPattern"]
   [timeZone="timeZone"]
   [var="varName"]
   [scope={page|request|session|application}"] />

12).   <fmt:parseDate>

Parses the string representation of dates and time that were formatted for a specific locale.

Syntax:

<fmt:parseDate value = "dateString"
   [type="{time|date|both}"]
   [dateStyle="{default|short|medium|long|full}"]
   [timeStyle="{default|short|medium|long|full}"]
   [pattern="customPattern"]
   [timeZone="timeZone"]
   [parseLocale="parseLocale"]
   [var="varName"]
   [scope={page|request|session|application}"] />

 

SQL Tags: 

The tags are used to achieve common database related tasks such as selection, insertion, deletion, updation from within the jsp pages, without using any java code.

1).  <sql:query>

This tag is used to query databases.

Syntax:

<sql:query sql="sqlQuery"
  var="varName" [scope="{page|request|session|application}"]
  [dataSource="dataSource"]
  [maxRows="maxRows"]
  [startRow="startRow"] />

2).   <sql:update>

This tag is used to execute SQL INSERT, UPDATE or DELETE statement. It is also used to execute Data Definition Language statements.

Syntax:

<sql:update sql="sqlUpdate"
  [dataSource="dataSource"]
  [var="varName"]
  [scope={page|request|session|application}" ] />

3).  <sql:setDataSource>

This tag is used to export a data source either as a scoped variable or as the data source configuration variable.

<sql: setDataSource
  {dataSource="dataSource" | url = "jdbcUrl" 
  [driver="driverClassName"]
  [user="userName"]
  [password="password"]}
  [var="varName"]
  [scope="{page|request|session|application}"] />

4).   <sql:param>

This tag is used to set the values of parameter.

Syntax:

<sql:param value="value"/>

5).   <sql:dateParam>

Sets the values of parameter markers in a SQL statement for values of type java.util.Date. It also works as a subtag of <sql:query> and <sql:update> tags.

Syntax:

<sql:dateParam value = "value" [type="{timestamp|time|date}"] />

6).  <sql:transaction>

This tag is used to set a transaction context for <sql:query> and <sql:update> subtags.

Syntax:

<sql:transaction [dataSource="dataSource"]
  [isolation=isolationLevel]>
   <sql:query> and <sql:update> statements
</sql:transaction>

isolationLevel ::= "read_committed"
   | "read_uncommitted"
   | "repeated_read"
   | "serializable"

 

 

XML Manipulating Tags in JSTL

XML stands for Extensible Markup Language. It was designed to describe data. It uses Document Type Definition (DTD) or XML Schema to describe the data.

Now a days the use of XML is increasing in the enterprises. Nowadays the XML is widely used exchanging information over the web.

The XML actions are divided in three categories:

  1. XML core actions.
  2. XML flow control actions.
  3. XML transform actions.

How we can access the XML document: The problem arises when we have to access the content of the XML. XPath, a W3C recommendation since 1999,  provides a way to  specify and selection of an XML document. The XML actions in JSTL is based on XPath.

XML core actions: These actions provide "Expression Language" support for XPath.   These actions are similar to the actions <c: out> and <c: set> . In this core actions one additional action has been added that is <x: parse>, which is used to parse an XML document in such a form which can be processed by the XPath engine.

For example: 

    <!-- It will parse an XML document -- >
  <c: import url = " http://roseindia.net/jsp" var = "rose" />
  <x: parse doc = "${doc}" var = "documentParsed"/> 

     <!-- It will access  XML data via XPath expressions -- >
   <x: out select = "$documentParsed/emailId"/>
  <x: out select = "$documentParsed/password"/>

  <!--It will set a scoped variable--  >
  <x: set var = "loginInformation" scope = "request" select = $documentParsed/emailId"/>

The commons tags are:

1).   <x: parse>:  This tag is used for parsing the XML document.

Syntax 1: 

When XML document specified via a String or Reader object

<x: parse { doc = "XMLDocument"| xml = "XMLDocument"}
  { var = "var" [scope = "scope"] | varDom = "var" [scopeDom = "scope"]}
  [systemId = "systemId"] [filter = "filter"] />

Syntax 2: 

When XML document specified via the body content  

  <x: parse { var = "var" [scope = "scope"] | varDom   = "var" [scopeDom = "scope"] }
  [systemId = "systemId"]
  [filter = "filter"] > XML Document to parse
  </x: parse> 

Attributes of <c: parse>

  1. doc:   XML document which has to be parsed. It is of type String, Reader.
  2. xml: We should use attribute doc instead of xml. This has been deprecated. It is of type String, Reader.
  3. systemId:  It is the system identifier used for parsing the XML document. It is of type String.
  4. filter: It is the filter which is to be applied to the source document. It is of type org.xml.sax.XMLFilter.
  5. var:  It is of type String. It is the name of the exported scoped variable for the parsed XML document.
  6. scope: It is the Scope defined for the attribute var. scope are page| request | session | application.
  7. varDom: It is the name of the exported scoped variable for the parsed XML document.
  8. scopeDom: It is the Scope for attribute varDom.

2).   <x: out>: It is used to evaluates an XPath expression and outputs the result to the current JspWriter object. 

Syntax : 

<x: out select = "XPathExpression" [escapeXml = "{true| false}"] />

Its body is empty.

Attributes of the <x: out> are:

  1. select:  This is the XPath expression which is to be evaluated. It is of type String. 
  2. escapeXml: This determines whether the special characters like <, >, &, ",' in the resulting string should be converted to their corresponding character entity codes. Character entity codes looks like &lt, &gt, &amp and many more.

3).   <x: set> :  This tag is used to evaluates an XPath expression and it stores the result into a scoped variable.

Syntax: 

<x: set select "XPathExpression" var = "varName" [scope = "{page| request | session| application"] />

Attribute of the <x: set> tag:

  1. select: This attribute stores the XPath expression which has to be evaluated. It is of type String.
  2. var: It is the name of the exported scoped variable which is used to hold the value specified in the action.
  3. scope: It is the Scope of  the var attribute. It can be either page, request, session, application. By default it is page. It is of type String.

XML Flow Control:
It provides the facility to easily parse and access XML data. This tag also provides us the ability to iterate over elements in an XML document and can also conditionally process JSP code depending on the result of an XPath expression.  

The tags in XML flow control are similar to the tags in EL flow control actions like <c: if>, <c: choose>, <c: forEach>. The difference between these two tags is that the XML flow control tags are applied to the XPath expressions. 

The common tags are:

1). <x: if> :  This tag is used to evaluates the XPath expression which is specified in the select attribute and the resulting result is converted to a boolean according to the semantics of the XPath boolean() funtion. This tag can have a body and may be empty body. In this tag there is nothing like else condition in the java.

Syntax without body content:

<x: if select = "XPathExpression" var = "varName" [scope = "{page| request| session| application} "] />

Syntax with body content:

<x: if select = "XPathExpression" [var = "varName"] [scope = "{page| request| session| application} "] />
  --------------body content-----------------
 </x: if>

Attributes of <c: if> tag

  1. select:  This attribute specifies an XPath expression. This expression is evaluated and result is converted to a boolean which indicates whether body content should be processed or not. By default it is false.
  2. var: It is name of the exported scoped variable which stores the result of the test condition.
  3. scope: It is the Scope for attribute var. The scope variables can be page, request, session and application.

2).  <x: choose>: It provides you the option to choose one of the right condition. It works like an if- else condition in java.  This action processes the body of the <x: when> actions>, if condition evaluates to true then that expression will be evaluated.  If none of the nested <x: when> actions evaluates to be true, then the body of an <c: otherwise> action will be processed. 

Syntax for <x: choose>

<x: choose>
  <x: when> 
  body content 
  </x: when> 
  <x: otherwise>
  body content
  </x: otherwise>
<x: choose>


3). <x: when> : This tag represents an alternative within an <x: choose> action. If the first <x: when> action in <c: choose> evaluates to be true, then the JSP container processes the body content within the <x: when> and writes it to the current JspWriter.

Syntax:

<x: when select = "XPathExpression">
   body content
</x: when>

Attribute of the <c: when> action

select :  It tells whether or not the body content should should be processed or not. 

Note: It must always written under <x: choose> action that is it is the child of <x: choose> tag.  This tag must appear before an <x: otherwise> action that is also the child of <x: choose> tag. 
 
4). <x: otherwise>:  If none of the nested <c: when> actions evaluates to be true, then the body of the <x: otherwise>  will be evaluated. This tag represents the last alternative within a <x: choose> action.

Syntax: 

<x: otherwise>
   conditional block
</x: otherwise>

This tag doesn't have any attribute. 

5). <x: forEach>: This tag is used to evaluates the given XPath expression. As long as there are items to iterate over, the body content of the tag <x: forEach> is processed by the Jsp container and written over the current JspWriter. This tag works like <c: forEach> tag in core action except the fact that it applies on XPath expression.

Syntax:

<x: forEach [var = "varName"] select = "XPathExpression" [varStatus = "varStatusName"] 
    [begin = "begin"]  [end = "end"]  [step = "step"]> 
  body content
</x: forEach>

Attributes of the <x: forEach>

  1. var:  Its value depends on the result of the XPath expression in the select attribute. It is the name of the exported scoped variable for the current item of the iteration. 
  2. select: It is the XPath to be evaluated.
  3. varStatus:  This tag contains the reference of the javax.servlet.jsp.jstl.core.LoopTagStatus. It is the name of the exported scoped variable for the status of the iteration. This variable has nested visibility.  
  4. begin:  Iteration begins at the item located at the specified index. The first item of the location has index 0. It must be greater or equal to 0. 
  5. end:  The iteration gets ends at the item located at the specified index. end should not be less than begin. 
  6. step: In this attribute we specify the how the item will be incremented. If we are specifying the step then it must be greater or equal to 1.  

XML Transform actions:

The XML transform actions supports the transformation of XML documents with XSLT stylesteets.  

The common tags are:

1). <x: transform>: It applies an XSLT stylesheet transformation to an XML document. 

Syntax 1: Without body content -----

<x: transform { doc = "XMLDocument"| xml = "XMLDocument"} xslt = "XSLTStylesheet" [docSystemId = "XMLSystemId"| xmlSystemId = "XMLSystemId"}] [ xsltSystemId = "XSLTSystemId"] [{var = "varName" [ scope = "scopeName"] | result = "resultObject"}]

Syntax  2 : With a body to specify transformation parameters -----

<x: transform { doc = "XMLDocument" | xml = "XMLDocument"} xslt = "XSLTStylesheet" [{ docSystemId = 
  "XMLSystemId"| xmlSystemId = "XMLSystemId"}] [xsltSystemId = "XSLTSystemId"]
  [{var = "varName" [scope = "scopeName"] | result = "resultObject"}]
  <x: param> actions
</transform>

Syntax 3: With a body to specify XML document and optional transformation parameters

<x: transform xslt = "XSLTStylesheet" [{docSystemId = "XMLSystemId"|xmlSystemId = "XMLSystemId"}]
  xsltSystemId = "XSLTSystemId" [{ var = "varName" [scope = "scopeName"] | result = "resultObject"}]
  XML Document to be parsed
  <x: param>  actions
</x: param>


Attributes of <x: transform>

  1. doc: It is the source XML document to be transformed. 
  2. xml: This attribute has been deprecated. We should use doc instead of using xml.
  3. xslt: This attribute is used to transform stylesheet as a String, Reader, or Source object.
  4. docSystemId: It is the system identifier which parsing the XML documents.
  5. xmlSystemId: This attribute has been deprecated. Try to use docSystemId.. 
  6. xsltSystemId: It is the system identifier used for parsing the XSLT stylesheet .
  7. var: It is the name of the exported scoped variable used for the transformed XML document.
  8. scope: This attibute can have scopeName as page, request, session, application.
  9. result: Here comes the object that captures or process the transformation result. 

2). <x: param>: This action must be nested within <x: transform> action to set the transformation parameter. We can specify the value of the parameter by using the value attribute or in the action's body content. 

Syntax 1: When we pass the parameter value in attribute "value"

<x: param name = "name" value = "value">

Syntax 2: When we specify the parameter value in the body content. 

<x: param name = "name">
  parameter value
</x: param>

Attributes of <x: param>

  1. name: It is the name of the transformation parameter. 
  2. value: It is the name of the parameter. 

 

Tag Library Validators (TLVs)

Tag library validation is part of the JSP 1.2 specification. Tag Library Validators are used to enforce certain constraint on JSP pages. Such constraints are not allowing the JSP author to write scriptlet ( Java code) or only to use specified tags within the page. 

This is a part of javax.servlet.jsp.jstl.tlv package. 

There are two types of validation provided in this libraray. 

1). ScriptFree : It gives the assurance of script- free pages.

2). PermittedTaglibs: It is the collection of permitted tag libraries on a page. 

JSTL I/O Tags:

 

It is possible to do common input and output related tasks directly from within the JSP. The I/O tag library provides support for protocols like HTTP, HTTPS, FTP, XML-RPC and SOAP.

IO Tags
request Requests the content of the given URL.
http Performs a HTTP request on the given URL with the specified action and optional body. If no action is specified then it defaults to "GET".
header Defines a URL or HTTP header for the current <request> or <http> tag. The value of the header can be specified via the value attribute otherwise the value of the tags body is taken instead.
param Defines a query argument for the URL of the current request. The value of the parameter can be specified as an attribute otherwise the value of the tags body is taken instead.
soap Performs a HTTP SOAP request on the given URL, SOAPAction and body.
xmlrpc Performs an XML RPC request on the given URL.
body Contains the body of a HTTP POST, XML-RPC or SOAP request which is sent so the URL as input.
pipe Acts like a Unix pipe between tags that are not capable of piping themselves. A pipe can take some input or some output or both.
get Returns the bean or bean property and pipes it into its parent PipeConsumer tag.