JSTL

JSTL: JSP standard Tag Library.

It is collection of Jsp Custom tags. Jar required for using this is jstl.jar

Why JSTL?

1) To simplefies the presenation layer.

2) Avoid scriptlets

3) Reusable component

4) Easy for non programmer or inexperienced as you don't require java knowledge

JSTL Consequences:

1) Processing overhead during jsp to servlet code translation, because lot of code will be added into servlet for custom tags.

2) Scrptlet are more powerfull then JSTL because in scriptlet we cna write any java languange code as required and in jstl we are limited to provided tags.

JSTL includes following tag libraries:

Core: http://java.sun.com/jsp/jstl/core Prefix:c

XML: http://java.sun.com/jsp/jstl/xml Prefix:x

Format: http://java.sun.com/jsp/jstl/fmt Prefix:fmt

SQL: http://java.sun.com/jsp/jstl/sql Prefix:sql

Functions: http://java.sun.com/jsp/jstl/functions Prefix:fn

JSTL Core Tags:

<c:out >

It specifies basic output action.

 e.g <c:out value=${1+2}/>

<c:set >

It specifies the basic variable setting.

 e.g <c:set var="calc" scope="session" value="${1000*2}"/>
    <c:out value="${name}"/>

<c:remove >

Removes a scoped variable

 e.g <c:remove var="name"/>

<c:catch>

Catches any Exception that occurs in its body.

 e.g <c:catch var ="expObj">
     <% int x = 3/0;%>
    </c:catch>

<c:if>

Conditional if action.

<c:if test = "${3>1}">
   Yes 3 is greater then 1.
</c:if>

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

Conditional Switch case statement.

 e.g <c:set var="val" scope="session" value="${1000*2}"/>
    <c:choose>
    <c:when test="${val <= 0}">
       Val is less then equal to zero
    </c:when>
    <c:when test="${val > 1000}">
        Val is more then thousand.
    </c:when>
    <c:otherwise>
        No Match
    </c:otherwise>
 </c:choose>

<c:import>

Retrieves contents of specfied page.

 e.g <c:import var="output" url="http://www.abc.com"/>
    <c:out value="${output}"/>

<c:forEach >

Iteration tag

 e.g <c:forEach var="i" begin="1" end="5">
    Values <c:out value="${i}"/><p>
    </c:forEach>

<c:forTokens>

Iterates over tokens, separated by the supplied delimeters.

 e.g <c:forTokens items="ank,ajay,piyush" delims="," var="name">
    <c:out value="${name}"/><p>
    </c:forTokens>

<c:param>

Adds a parameter to a containing 'import' tag's URL.

 e.g <c:url value="/getData.jsp" var="getdata">
   <c:param name="id" value="ank"/>
    </c:url>

<c:redirect >

Redirects to a new URL.

 e.g <c:redirect url="http://www.abc.com"/>

<c:url>

Creates a URL.

 e.g <c:url value="/getData.jsp" var="getdata">
   <c:param name="id" value="ank"/>
   </c:url>

Formatting Tags:

<fmt:formatNumber>

To display the numerical value in a specific format.

 e.g <c:set var="amt" value="180.2139" />
<p>Formatted Output: <fmt:formatNumber type="percent" 
            maxIntegerDigits="3" value="${amt}" /></p>

Output: Formatted Output: 021%

<fmt:parseNumber>

Parse the string in number format.

 e.g: <fmt:parseNumber var="i" type="number" value="${amt}" />

Ouput: 180

<fmt:formatDate>

Formats a date or time using the specefied styles and pattern

 e.g <c:set var="dt" value="<%=new java.util.Date()%>" />

 <p>Date: <fmt:formatDate type="date" 
            value="${dt}" /></p>

Output: 28-Jun-2014

<fmt:parseDate>

Parses the string representation of a date or time

 e.g <c:set var="dt" value="28-06-2014" />

<fmt:parseDate value="${dt}" var="parsedMyDate" 
                              pattern="dd-MM-yyyy" />
<p>Parsed Date: <c:out value="${parsedMyDate}" /></p>

Output: Parsed Date: Sat Jun 28 14:27:53 GST 2014

<fmt:bundle>

Loads a resource bundle to be used by its tag body.

 e.g <fmt:bundle basename="msg">
    Hello: <fmt:message key="hi">
    <fmt:bundle>

<fmt:setLocale>

It stores the specifc locale in the configuration variable.

 e.g <fmt:setLocale value="en_US">

<fmt:setBundle>

Loads a resource bundle and stores it in the configuration variable.

 e.g <fmt:setBundle basename="msg" var="prop"/>

<fmt:message key="hi" bundle="${prop}"/><br/>

<fmt:timeZone>

Specifies the timeZone.

 e.g <c:set var="dt" value="<%=new java.util.Date()%>" />
	<fmt:formatDate value="${now}" type="both"
		      timeStyle="long" dateStyle="long" />

Output: 28-Jun-2014 14:42:49

<fmt:setTimeZone>

Stores the given time zone in the time zone configuration variable

 e.g <fmt:setTimeZone value="GMT-8" />
<p>Date: <fmt:formatDate value="${dt}" 
       type="both" timeStyle="long" dateStyle="long" /></p>

Output: Date: 28 June 2014 11:02:37 GMT-08:00

<fmt:message>

It looks for a localized message in bundle

 e.g <fmt:bundle basename="msg">
    Hello: <fmt:message key="hi">
    <fmt:bundle>

<fmt:requestEncoding>

Sets the request character encoding


 e.g <fmt:requestEncoding value="UTF-8" />

XML Tags:

For all example suppose we have a xml:

<c:set var="test">
<employees>
    <emp>
      <name>Ank</name>
      <sal>60000</author>
     </emp>
    <emp>
      <name>Ajay</name>
      <sal>61000</sal>
    </emp>
</employes>
</c:set>

<x:out>

It specifies basic output action.

 e.g <x:out select="$output/employees/emp[1]/name" />

<x:parse>

Parse XML data

 e.g
<x:parse xml="${test}" var="output"/>

<x:set >

Sets a variable to the value

 e.g
<x:set var="name" select="$output/employees/emp[1]/name"/>

<x:if >

Evaluates the condition

 e.g <x:if select="$output/employees[1]/emp/sal > 10000">
   Salary is to high
</x:if>

<x:forEach>

Iterate a loop.

 e.g <x:forEach select="$output/employees/emp/name" var="item">
   <li>Emp Name: <x:out select="$item" /></li>
</x:forEach>

<x:choose>,<x:when >,<x:otherwise >

It is like a switch case statement

 e.g <x:choose>
   <x:when select="$output//emp/name = 'Ank'">
      Name is Ank
   </x:when>
   <x:when select="$output//emp/name = 'Ajay'">
      Name is Ajay
   </x:when>
   <x:otherwise>
      Not Found.
   </x:otherwise>
</x:choose>

<x:transform >

Applies an XSL transformation on a XML document

For this tag we need to write xsl style sheet to apply the style on a xml document to disaply data in a specific format.

<xsl:template match="employees">
  <table border="1" width="100%">
    <xsl:for-each select="emp">
      <tr>
        <td>
          <i><xsl:value-of select="name"/></i>
        </td>
       <td>
          <xsl:value-of select="sal"/>
        </td>
      </tr>
    </xsl:for-each>
  </table>
</xsl:template>

And then

<c:import url="style.xsl" var="xslt"/>
<x:transform xml="${test}" xslt="${xslt}"/>

And then ouput will be represented in a tabular format.

<x:param >

It is used with above mentioned transform tag.

 e.g <x:transform xml="${test}" xslt="${xslt}">
   <x:param name="bgColor" value="yellow"/>
</x:transform>

Table background will be yellow.

Function Tags:

For all example cosider that we have set a string in a variable:

<c:set var="strObj" value="My name is Ank"/>

fn:contains()

Checks if input string contains the specified string.

 e.g <c:if test="${fn:contains(strObj, 'Ank')}">
   <p>String Found<p>
</c:if>

fn:containsIgnoreCase()

Ignore case while cheking string.

 e.g <c:if test="${fn:containsIgnoreCase(strObj, 'aNk')}">
   <p>String Found<p>
</c:if>

fn:endsWith()

Checks if the strin ends with a specified suffix

 e.g <c:if test="${fn:endsWith(strObj, 'Ank')}">
   <p>String ends with Ank<p>
</c:if>

fn:escapeXml()

Escapes characters.

 e.g <c:set var="strobj1" value="This <abc>is another String.</abc>"/>
	<p>String with xml tags : ${fn:escapeXml(string2)}</p>

fn:indexOf()

returns the index of specified string.

 e.g 
<p>Index of Ank : ${fn:indexOf(strobj, "Ank")}</p>
Output: Index of Ank : 11

fn:split()

Splits a string.

 e.g <c:set var="str1" value="${fn:split(strObj, ' ')}" />

fn:join()

Joins all elements of an array into a string.

 e.g <c:set var="str2" value="${fn:join(str1, '-')}" />
Output will be: My-name-is-Ank

fn:length()

Returns the length of string.

 e.g <p>Length of strObj: ${fn:length(strObj)}</p>
Output: Length of strObj: 14

fn:replace()

Replace all occurences of a string with a specified string.

 e.g <c:set var="str1" value="${fn:replace(strObj, 
                                'Ank', 'Ajay')}" />

fn:startsWith()

Checks if the strin ends with a specified prefix

 e.g <c:if test="${fn:startsWith(strObj, 'My')}">
   <p>String starts with My<p>
</c:if>

fn:substring()

Returns a subset of a string.

 e.g <c:set var="str1" value="${fn:substring(strObj, 5, 14)}" />
<p>Sub string : ${str1}</p>
Output Will be: Sub string : me is Ank

fn:substringAfter()

Returns a subset of a string following a specific substring.

 e.g <c:set var="str1" value="${fn:substringAfter(strObj, 'is')}" />

fn:substringBefore()

Returns a subset of a string before a specific substring.

 e.g <c:set var="str1" value="${fn:substringBefore(strObj, 
                                            'Ank')}" />

fn:toLowerCase()

Converts all characters of a string to lower case.

 e.g <c:set var="str1" value="${fn:toLowerCase(strObj)}" />

fn:toUpperCase()

Converts all characters of a string to upper case.

 e.g <c:set var="str1" value="${fn:toUpperCase(strObj)}" />

fn:trim()

Removes white spaces from both ends of a string.

 e.g <c:set var="str1" value="${fn:trim(strObj)}" />

SQL Tags:

<sql:setDataSource>

To creates a simple DataSource

 e.g 
<sql:setDataSource var="ds" driver="com.mysql.jdbc.Driver"
     url="jdbc:mysql://localhost/ABC"
     user="username"  password="password123"/>
 

<sql:query>

Executes the specified SQL query

 e.g <sql:query dataSource="${db}" var="result">
SELECT * from tableName;
</sql:query>

<sql:update>

Executes the Specified update SQL query.

 e.g <sql:update dataSource="${db}" var="cnt">
   INSERT INTO tableName VALUES ();
</sql:update>

<sql:param>

Sets a parameter in an SQL statement

 e.g <sql:update dataSource="${db}" var="cnt">
  DELETE FROM tableName WHERE col1 = ?
  <sql:param value="123" />
</sql:update>

<sql:dateParam>

Sets a date parameter in an SQL statement.

 e.g Date dob = new Date("1988/09/25"); 
<sql:dateParam value="<%=dob%>" type="DATE" />

<sql:transaction >

To executes a set of statement in one shot as a transaction.

 e.g <sql:transaction dataSource="${db}">
<sql:update var="cnt1">
  DELETE FROM tableName WHERE col1 = ?
  <sql:param value="123" />
</sql:update>
<sql:update  var="cnt2">
   INSERT INTO tableName VALUES ();
</sql:update>
</sql:transaction>