Vous êtes sur la page 1sur 12

JSTL (JAVA STANDARD TAG LIBRARY)

The Java Server Pages Standard Tag Library (JSTL) is a collection of useful JSP tags which
encapsulates core functionality common to many JSP applications.
The JSP Standard Tag Library (JSTL) represents a set of tags to simplify the JSP development.
JSTL has support for common, structural tasks such as iteration and conditionals, tags for
manipulating XML documents, internationalization tags, and SQL tags. It also provides a
framework for integrating existing custom tags with JSTL tags.
Advantage of JSTL
1. Fast Developement : JSTL provides many tags that simplifies the JSP.
2. Code Reusability :We can use the JSTL tags in various pages.
3. No need to use scriptlet tag : It avoids the use of scriptlet tag.
There JSTL mainly provides 5 types of tags:
Tag Name

Description

core tags

The JSTL core tag provide variable support, URL management, flow control
etc.
The url for the core tag is http://java.sun.com/jsp/jstl/core .
The prefix of core tag is c.

sql tags

The JSTL sql tags provide SQL support.


The url for the sql tags is http://java.sun.com/jsp/jstl/sqland prefix is sql.

xml tags

The xml sql tags provide flow control, transformation etc.


The url for the xml tags is http://java.sun.com/jsp/jstl/xml and prefix is x.

formatting tags The formatting tags provide support for message formatting, number and date
formatting etc.
The url for the formatting tags is http://java.sun.com/jsp/jstl/fmt and prefix
is fmt.
functions tags

The functions tags provide support for string manipulation and string length.
The url for the functions tags is http://java.sun.com/jsp/jstl/functions and

prefix is fn.
Core Tags:
The core group of tags are the most frequently used JSTL tags. Following is the syntax to
include JSTL Core library in your JSP:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
There are following Core JSTL Tags:

<c:remove >

Removes a scoped variable (from a particular scope, if


specified).

<c:catch>

Catches any Throwable that occurs in its body and optionally


exposes it.

<c:if>

Simple conditional tag which evalutes its body if the supplied


condition is true.

<c:choose>

Simple conditional tag that establishes a context for mutually


exclusive conditional operations, marked by <when> and
<otherwise>

<c:when>

Subtag of <choose> that includes its body if its condition


evalutes to 'true'.

<c:otherwise >

Subtag of <choose> that follows <when> tags and runs only if


all of the prior conditions evaluated to 'false'.

<c:import>

Retrieves an absolute or relative URL and exposes its contents


to either the page, a String in 'var', or a Reader in 'varReader'.

<c:forEach >

The basic iteration tag, accepting many different collection


types and supporting subsetting and other functionality .

Core Tags
The JSTL core tags mainly provides 4 types of tags:
miscellaneous tags: catch and out.
url management tags: import, redirect and url.
variable support tags: remove and set.
flow control tags: forEach, forTokens, if and choose.

Syntax for defining core tags


<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
c:catch
It is an alternative approach of global exception handling of JSP. It handles the exception and
doesn't propagate the exception to error page. The exception object thrown at runtime is stored in
a variable named var.
Example of c:catch
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:catch>int a=10/0;</c:catch>

c:out
It is just like JSP expression tag but it is used for exression. It renders data to the page.
Example of c:out
index.jsp
<form action="process.jsp" method="post">
FirstName:<input type="text" name="fname"/><br/>
LastName:<input type="text" name="lname"/><br/>

<input type="submit" value="submit"/>


</form>
process.jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
First Name:<c:out value="${param.fname}"></c:out><br/>
Last Name:<c:out value="${param.lname}"></c:out>

c:import
It is just like jsp include but it can include the content of any resource either within server or
outside the server.
Example of c:import
This example uses c:import to display the content of other site.
index.jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<h1>Google.com</h1>
<c:import url="http://www.google.com"></c:import>
Let's see the simple example of c:import to display the source code of other site.
index.jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<h1>Google.com</h1>
<c:import var="data" url="http://www.google.com"></c:import>
<h2>Data is:</h2>
<c:out value="${data}"></c:out>
c:forEach
It repeats the nested body content for fixed number of times or over collection.

Example of c:forEach
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:forEach var="number" begin="5" end="10">
<c:out value="${number}"></c:out>
</c:forEach>

c:if
It tests the condition.
Example of c:if
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:set var="number" value="${200}">
<c:if test="${number<500}">
<c:out value="number is less than 500"></c:out>
</c:if>

c:redirect
It redirects the request to the given url.
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:redirect url="http://www.google.com"></c:redirect>

SQL tags:
The JSTL SQL tag library provides tags for interacting with relational databases (RDBMSs)
such as Oracle, mySQL, or Microsoft SQL Server.
Following is the syntax to include JSTL SQL library in your JSP:
<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>

Following is the list of SQL JSTL Tags:

<sql:transaction >

Provides nested database action elements with a shared Connection, set up to


execute all statements as one transaction.

sql:setDataSource
The <sql:setDataSource> tag sets the data source configuration variable or saves the data-source
information in a scoped variable that can be used as input to the other JSTL database actions.
<sql:setDataSource var="snapshot" driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost/TEST"
user="user_id" password="mypassword"/>
<sql:query dataSource="${snapshot}" sql="..." var="result" />

sql:query
The <sql:query> tag executes an SQL SELECT statement and saves the result in a scoped variable.

<sql:setDataSource var="snapshot" driver="com.mysql.jdbc.Driver"


url="jdbc:mysql://localhost/TEST"
user="root" password="pass123"/>

<sql:query dataSource="${snapshot}" var="result">


SELECT * from Employees;
</sql:query>

sql:update
The <sql:update> tag executes an SQL statement that does not return data, for example SQL
INSERT, UPDATE, or DELETE statements.
<sql:setDataSource var="snapshot" driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost/TEST"
user="root" password="pass123"/>

<sql:update dataSource="${snapshot}" var="count">


INSERT INTO Employees VALUES (104, 2, 'Nuha', 'Ali');
</sql:update>

<sql:query dataSource="${snapshot}" var="result">


SELECT * from Employees; </sql:query>

sql:param
The <sql:param> tag used as a nested action for <sql:query> and <sql:update> to supply a value
for a value placeholder. If a null value is provided, the value is set to SQL NULL for the
placeholder.
<sql:update dataSource="${snapshot}" var="count">
DELETE FROM Employees WHERE Id = ?
<sql:param value="${empId}" />
</sql:update>
sql:transactions
The <sql:transaction> tag is used to group <sql:query> and <sql:update> into transactions. You
can put as many <sql:query> and <sql:update> as statements inside <sql:transaction> to make
them a single transaction.

It ensures that the database modifications performed by the nested actions are either committed
or rolled back if an exception is thrown by any nested action.
<sql:transaction dataSource="${snapshot}">
<sql:update var="count">
UPDATE Students SET last = 'Ali' WHERE Id = 102
</sql:update>
<sql:update var="count">
UPDATE Students SET last = 'Shah' WHERE Id = 103
</sql:update>
<sql:update var="count">
INSERT INTO Students
VALUES (104,'Nuha', 'Ali', '2010/05/26');
</sql:update>
</sql:transaction>

<sql:query dataSource="${snapshot}" var="result">


SELECT * from Students;
</sql:query>

XML tags:
The JSTL XML tags provide a JSP-centric way of creating and manipulating XML documents.
Following is the syntax to include JSTL XML library in your JSP.
The JSTL XML tag library has custom tags for interacting with XML data. This includes parsing
XML, transforming XML data, and flow control based on XPath expressions.
<%@ taglib prefix="x"

uri="http://java.sun.com/jsp/jstl/xml" %>

<x:if >

Evaluates a test XPath expression and if it is true, it processes its body. If


the test condition is false, the body is ignored.

Example:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>

<html>
<head>
<title>JSTL Tags</title>
</head>
<body>
<h3>Books Info:</h3>
<c:set var="xmltext">
<books>
<book>
<name>Padam History</name>
<author>ZARA</author>
<price>100</price>
</book>
<book>
<name>Great Mistry</name>

<author>NUHA</author>
<price>2000</price>
</book>
</books>
</c:set>

<b>The title of the first book is</b>:


<x:out select="$output/books/book[1]/name" />
<br>
<b>The price of the second book</b>:
<x:out select="$output/books/book[2]/price" />

<x:parse xml="${xmltext}" var="output"/>


<x:set var="fragment" select="$output//book"/>
<b>The price of the second book</b>:
<c:out value="${fragment}" />

<ul class="list">
<x:forEach select="$output/books/book/name" var="item">
<li>Book Name: <x:out select="$item" /></li>
</x:forEach>
</ul>

<x:if select="$output/books[1]/book/price > 100">

Book prices are very high


</x:if>
</body></html>

Formatting tags
The JSTL formatting tags are used to format and display text, the date, the time, and numbers for
internationalized Web sites. Following is the syntax to include Formatting library in your JSP:

<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

<c:set var="balance" value="1250003.350" />

<fmt:parseNumber var="i" type="number" value="${balance}" />


<p>Parsed Number (1) : <c:out value="${i}" /></p>
<fmt:parseNumber var="i" integerOnly="true"
type="number" value="${balance}" />
<p>Parsed Number (2) : <c:out value="${i}" /></p> //round off the number
float to int

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


<p>Formatted Date (1): <fmt:formatDate type="time" value="${now}"
/></p>//Formatted Date (1): 14:27:18

<p>Formatted Date (2): <fmt:formatDate type="date" value="${now}"


/></p>//Formatted Date (2): 23-Sep-2010
<p>Formatted Date (3): <fmt:formatDate type="both" value="${now}"
/></p> //Formatted Date (3): 23-Sep-2010 14:27:18
<c:set var="now" value="20-10-2010" />
<fmt:parseDate value="${now}" var="parsedEmpDate" pattern="dd-MMyyyy" />
<p>Parsed Date: <c:out value="${parsedEmpDate}" /></p> //Parsed Date:
Wed Oct 20 00:00:00 GST 2010