This is a set of notes that i created from matter i could collect from the net.
JSTL
What Exactly Is the JSTL?
JSTL is the JSP Standard Tag Library. The JSTL came about under JSR-52 of the Java Community Process (JCP). These tag libraries provide a wide range
of custom action functionality.
- The JSTL encapsulates common functionality that a typical JSP author would encounter.
- The JSTL is a set of custom actions that is based on the JSP 1.2 and Servlet 2.3 specifications.
While the JSTL is commonly referred to as a single tag library, it is actually composed of four separate tag libraries:
1. Core
2. XML manipulation
3. SQL
4. Internationalization and formatting
5. Function Tags
Features
. These libraries are defined by the Tag Library Descriptor files.
. Using separate TLDs to expose the tags, the functionality for each set of actions is apparent and makes more sense.
. Using separate TLDs also allows each library to have its own namespace.
-----------------------------------------------------------------------------------------------------------------------------
JSTL Tag Libraries
1. Core library
- The Core library provides general-purpose actions that get and set scoped variables, write to the JspWriter, and handle catching exceptions.
- The actions in Core library also take advantage of the expression language features.
- Also included in the Core library are those actions related to conditional processing, handling iterations, and dealing with URL resources.
Ex:
< c:out value="Hello my friend" />
2. XML library
- It relates to supporting XML manipulation in pages.
- The actions in this library have to do with parsing and writing XML content, handling flow control, and doing transformations.
Ex: XML DOM parsing
<!-- parse an XML document -->
<c:import url="http://www.mkp.com/booklist.xml" var="xml"/>
<x:parse source=${xml}" var="doc"/>
<!-- access XML data via XPath expressions -->
<x:out select="$doc/title"/>
<!-- set a scoped variable -->
<x:set var="bookTitle" scope="request" select="$doc/title"/>
3. SQL library
- The SQL library provides the capabilities to interact with databases.
- This includes dealing with data sources, doing queries, updates, and transactions.
- Using the SQL actions in combination with iteration actions makes it very easy to loop through result sets.
Ex: Displaying Result Sets
<sql:query var="bookList" dataSource="${datasource}">
SELECT * FROM books WHERE title = ‘JSTL’ ORDER BY author
</sql:query>
<table>
<c:forEach var="book" items="${bookList.row}">
<tr>
<td><c:out value="${book.title}" /></td>
<td><c:out value="${book.author}" />
</td>
</tr>
</c:forEach>
</table>
4. International and Formatting library
- The International and Formatting library is concerned with actions that deal with assisting page authors in internationalizing their application.
- This includes actions related to locales and resource bundles, date, time and timezone issues.
Ex: Using International Messages
<fmt:message key="welcome">
<fmt:param value="${visitCount}" />
<fmt:message/>
------------------------------------------------------------------------------------------------------
JSTL Requirements
The requirements to use JSTL are:
- A JSP server - Tomcat from apache.org.
- A JSTL implementation - Tablib from apache.org, jstl.jar and standard.jar.
- A JSTL document - JSTL specification from jcp.org.
- JSP pages with JSTL tags - You write them.
----------------------------------------------------------------------------------------------------------------------------
Expression Language
The expression language (EL) allows for a much simpler syntax for doing application data manipulation for the page author.
Expressions in JSTL look like this:
${expression}
They start with ${ and end with }; whatever comes between these two markers is treated as an expression.
Implicit Objects
- There are quite a few implicit objects exposed through the EL.
- These objects allow for access to any variables that are held in the particular JSP scopes.
- Objects include pageScope, requestScope, sessionScope, and applicationScope.
Object Name Description
------------ ------------
pageScope Collection of all variables in page scope
requestScope Collection of all variables in request scope
sessionScope Collection of all variables in session scope
applicationScope Collection of all variables in application scope
param Request parameters for this page
paramValues All parameter values for a parameter
header Headers sent by the web browser
headerValues All values for a particular header
initParam A context initialization parameter
cookie Value of a cookie
pageContext Allows access to page information
Ex:
1. ${pageContext.request.servletPath}
- will return the Servlet path obtained from the HttpServletRequest.
2. ${sessionScope.loginId}
- will return the session-scoped attribute named “loginId” ,or null if the attribute is not found.
3. ${param.bookId}
- will return the String value of the “bookId” parameter, or null if it’s not found.
4. ${paramValues.bookId}
- will return the String[] containing all values of the bookId parameter, or null if it’s not found.
-----------------------------------------------------------------
Accessing Data Structures
There are two ways provided by the EL to access data structures. The operators are . and [] .
1. Using the . (also called dot) notation is a shortcut for accessing an object’s property.
Ex: The book <c:out value="${book.title}"/> is currently out of stock.
2. The [] is used for accessing collections. This includes lists, maps, and arrays.
Ex: Book Description: <c:out value="${bookDesc[book.isbn]}"/>
--------------------------------------------------------------------
EL Operators
1. Relational Operators
- These operators include: ==, !=, <, >, <=, >=, eq, ne, lt, gt, le, and ge.
- The last six operators are made available to avoid having to use entity references in XML syntax.
2. Other Operators
There are also arithmetic and logical operators that can be used with the EL.
Arithmetic operators consist of addition (+), subtraction (-), multiplication (*), division (/ or div), and remainder/modulo (% or mod).
Logical operators consist of &&, ||, and !. These represent and, or, and not, respectively.
Usage Examples
- ${1 == 1}
- ${1 != 1}
- ${1 <= 1}
- ${1 le 1}
- ${1 == 1 || 2 > 3}
- ${1 == 1 and 2 > 3}
- ${6 * 5 == 30}
- ${param.name == ‘Sue’}
- ${empty param.name}
- ${(not empty param.name && param.name == \"Sue\") and (param.month == 9)}
Ex:
<c:if test="${1 == 1}">
<b> Equals operator</b>
</c:if>
----------------------------------------------------------------------------------------
Core Actions
The Core area comprises four distinct functional sections:
- General-purpose actions that are used to manipulate the scoped variables that might be found within a JSP. These general-purpose actions also encompass error handling.
- Conditional actions used for doing conditional processing within a JSP.
- Iterator actions that make it easy to iterate through collections of Objects.
- URL-related actions for dealing with URL resources in a JSP.
Taglib Directive
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
1. Writing Output to the JspWriter
The <c:out> tag is used to output to the current JspWriter. This is similar to using the JSP expression <%= scripting language expression %>
Usage - <c:out value="text_mixed_with_expressions"/>
Ex: JSTL Form
<c:out value="${sessionScope.bookInfo.title}">
JSP Form
<%@ page import="com.mk.jstl.bookInfo" %>
<% BookInfo bookInfo = (BookInfo)session.getAttribute("bookInfo");
%>
The title of the book you just purchased is
<% = bookInfo.getTitle() %>
Ex:(2)
<c:out value=${myData} escapeXml="false" />
Ex:(3)
<c:out value="${param.name}" default="my friend"/>
If no parameter is specified called name, then the default value of “my friend” will appear
2. Setting Variables
The <c:set> tag is used to set the value of a scoped variable in any JSP scope, or is used to set a property of a specified target object.
It is possible to set the value attribute using the EL or to set the value by using the body content of the tag.
Usage - <c:set var="name" value="expression"/>
Ex:
<c:set value="<b>I love to ride my bicycle</b>" var="myData"/>
-------------------------
<c:set var="myData2" scope="session" >
<b>I love to ride my bicycle</b>
</c:set>
----------------
It’s possible to access a parameter using
<c:out value="${param.name}" />
Update the value using
<c:set var="param.name" value="some new value" />
----------------------
<c:set var="newVar" value="${param.name}" />
Value of initial parameter name: <c:out value="${newVar}"/>
<c:set var="newVar" value="another value" />
Value after an update: <c:out value="${newVar}"/>
------------------------------------------------
Concatenating Strings in the EL
<c:set var="phone" value="(${param.areacode})-${param.number} x(${param.ext})"/>
The phone number is: <c:out value="${phone}" />
------------------------------------------------------
Using <c:set> with Target Objects
<jsp:useBean id="list" class="java.util.TreeMap" />
<c:set target="${list}" property="${param.name}" value="1" />
<c:set target="${list}" property="Zuni" value="2" />
<c:set target="${list}" property="Amy" value="3" />
<c:set target="${list}" property="Liz" value="4" />
<c:set target="${list}" property="Les" value="5" />
<%-- Print out the list of keys to see the sort --%>
<c:forEach var="item" items="${list}" >
<c:out value="${item.key}" />,<c:out value="${item.value}" />
<br>
</c:forEach>
--------------------------------------------------------------------
3. Removing Variables
Removing variables that have been set in any scope using <c:set> is done with the <c:remove> action.
Ex:
<c:set value="<b>I love to ride my bicycle</b>" var="myData" scope="application"/>
<c:set value="<b>I love to ride my bicycle</b>" var="myData2" scope="session" />
<c:remove var="myData" scope="session" />
<c:remove var="myData" scope="application" />
<c:remove var="myData2" />
4. Handling Exceptions
The <c:catch> action is a way to handle exceptions. It can handle errors from any action as well as from multiple actions at once by nesting those actions within <c:catch>.
Ex:
<c:catch var="urlError">
<c:import url="" />
</c:catch>
<c:if test="${not empty urlError}">
<b>Your file was not found.</b>
<br>
Here’s more information on the error:
<br><font color="#FF0000">
<c:out value="${urlError}" />
</font>
</c:if>
The scope of var will always be page. If no error is thrown, then the var is removed from the scope when the </c:catch> is encountered.
5. Decisions—Conditional Actions
The JSTL supports both simple and mutually exclusive conditional actions.
The actions that are used to do conditional processing are the <c:if> for simple conditions, and a combination of <c:choose>, <c:when>, and <c:otherwise> for handling mutually exclusive conditions.
The <c:if> and <c:when> both have the test attribute in common.Using the test attribute, a boolean expression is evaluated. This expression is constructed using the EL. If the test condition evaluates to true, then the body content of the action is executed. If the test condition is false, then the body content is skipped.
5.1) Simple Conditional
The <c:if> action provides a simple conditional action. If the test condition specified evaluates to true, then the body content is evaluated.
Usage - <c:if test="expression"/> body </c:if>
Ex: <c:if test="${user.previousOrders == 0}">
Welcome to the bookstore.
</c:if>
5.2) Mutually Exclusive Conditionals
When using a mutually exclusive conditional action, only one of the number of possible alternative actions gets its body content evaluated. This is the familiar if/else or if/then/else programming structure. The JSTL actions <c:choose>, <c:when>, and <c:otherwise> are used to construct mutually exclusive conditional statements.
Usage - <c:choose>
<c:when test="expression">
body
</c:when>
<c:when test="expression">
body
</c:when>
...
...
<c:otherwise>
body
</c:otherwise>
</c:choose>
Ex:
<c:choose>
<c:when test="${user.lastPurchaseAmount > 100}">
Welcome big spender, check out all the new titles you can buy!
</c:when>
<c:when test="${user.lastPurchaseAmount > 30}">
Welcome, we’ve got some new titles that you might be interested in!
</c:when>
<c:when test="${user.lastPurchaseAmount > 1}">
Welcome, let us help you find some great books!
</c:when>
<c:otherwise>
Come on, there has to be something that you can buy!
</c:otherwise>
</c:choose>
Ex: Switch Functionality Using <c:choose>
<c:choose>
<c:when test="${current.first}" >
<td><font color="#0000FF">
<c:out value="${book.title}"/>
</font></td>
</c:when>
<c:when test="${current.count % 2 == 1 }" >
<td><font color="#FF0000">
<c:out value="${book.title}"/>
</font></td>
</c:when>
<c:otherwise>
<td><c:out value="${book.title}"/></td>
</c:otherwise>
</c:choose>
Ex: If/Then/Else Functionality Using <c:choose>
<c:choose>
<c:when test="${current.first}" >
<td><font color="#0000FF">
<c:out value="${book.title}"/>
</font></td>
</c:when>
<c:otherwise>
<td><c:out value="${book.title}"/></td>
</c:otherwise>
</c:choose>
6. Handling Iterators
There are two iterations actions <c:forEach> and <c:forTokens>.
<c:forEach> repeats over a nested body content .All of the standard J2SE java.util.Collection and java.util.Map types are supported in the <c:forEach> action. These include:
List
LinkedList
ArrayList
Vector
Stack
Set
HashMap
Hashtable
Properties
Provider
Attributes
The <c:forTokens> action is useful for parsing through tokens that are separated by some delimiter.
6.1) <c:forEach>
Usage : <c:forEach var="name" items="expression" begin="expression" end="expression" step="expression">
body
</c:forEach>
Ex: Looping through a collection of books.
<table>
<c:forEach var="book" items="${books}" varStatus="status">
<tr>
<td><c:out value="${book.title}"/></td>
</tr>
</c:forEach>
</table>
Ex: we only want to display the first ten books in our collection
<table>
<c:forEach var="book" items="${books}" varStatus="status" begin="0" end="9">
<tr>
<td><c:out value="${book.title}"/></td>
</tr>
</c:forEach>
</table>
Ex: print the first ten books, and highlight the first five
<table>
<c:forEach var="book" items="${books}" varStatus="status" begin="0" end="9">
<tr>
<c:choose>
<c:when test="${status.count < 4}">
<td bgcolor="#FFFF00">
<c:out value="${book.title}"/>
</td>
</c:when>
<c:otherwise>
<td><c:out value="${book.title}"/></td>
</c:otherwise>
</c:choose>
</tr>
</c:forEach>
</table> >
Ex: Dealing with large collections
//Setting the Variables for the Iteration
<c:set var="totalSize" scope="session" value="40"/>
<c:set var="chunkSize" scope="session" value="10"/>
<c:set var="start" scope="page" value="1"/>
<c:set var="finish" value="${start + chunkSize - 1}" />
//<c:forEach> Iteration
<c:forEach var="item" varStatus="current" begin="${start}" end="${finish}">
Item: <c:out value="${item}"/>
Current count =<c:out value="${current.count}" />
Current index =<c:out value="${current.index}" />
<br>
<c:if test="${current.index == finish}" >
<c:out value="- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -" />
</c:if>
</c:forEach>
LoopTagStatus properties
Property Type
current Object
index int
first boolean
last boolean
begin int
Ex: Looping with a Collection
Setting up the Collection
<jsp:useBean id="list" class="java.util.Vector" />
<%-- Add some values to the Vector, so that we can loop over them --%>
<%
list.add("apple");
list.add("orange");
list.add("plum");
list.add("peach");
%>
Looping over the Vector
<%-- Print out the Vector collection --%>
<c:forEach var="item" items="${list}" >
<c:out value="${item}" />
<br>
</c:forEach>
Iterating through the Collection
<c:forEach var="item" items="${list}" begin="1" step="2" end="5">
<c:out value="${item}" />
<br>
</c:forEach>
Accessing a Map.Entry Object from a Map
<jsp:useBean id="list" class="java.util.TreeMap" />
<%-- Add the properties into the TreeMap that we want sorted --%>
<%-- Note, the order is incorrect when we add the values --%>
<c:set target="${list}" property="${param.name}" value="1" />
<c:set target="${list}" property="Zuni" value="2" />
<c:set target="${list}" property="Amy" value="3" />
<c:set target="${list}" property="Liz" value="4" />
<c:set target="${list}" property="Les" value="5" />
<%-- Print out the list of keys to see the sort --%>
<c:forEach var="item" items="${list}" >
<c:out value="${item.key}" />,<c:out value="${item.value}" />
<br>
</c:forEach>
Indexing a HashMap Value Using a Key
<jsp:useBean id="hash" class="java.util.HashMap" />
<%-- Add some values, so that we can loop over them --%>
<%
hash.put("apples","pie");
hash.put("oranges","juice");
hash.put("plums","pudding");
hash.put("peaches","jam");
%>
<br>
<c:forEach var="item" items="${hash}">
I like to use <c:out value="${item.key}" /> to make
<c:out value="${hash[item.key]}" />
<br>
<br>
</c:forEach>
6.2) Tokenizing Data Using <c:forTokens>
When using the <c:forTokens>, you specify a string in the items attribute. Using the delims attribute, you specify what the delimiter characters are. This can be one character, like a comma, or any number of characters.
Usage :
<c:forTokens var="name" items="expression" delims="expression" begin="expression" end="expression" step="expression">
body
</c:forTokens>
Ex: <c:forTokens> with a null delims Attribute
<%-- set some tokens to work with --%>
<c:set var="tokens" value="a,b,c:d:e,f#g,h" />
<%-- Tokenize using null delim --%>
<b>Tokenize the string "<c:out value="${tokens}" />" with a null
delimiter</b>
<br>
<c:forTokens var="token" items="${tokens}" delims="" >
Found token: <c:out value="${token}" /><br>
</c:forTokens>
Ex: <c:forTokens> with delims Value
<%-- Tokenize using 1 delim --%>
<b>Tokenize the string "<c:out value="${tokens}" />" with delims = ","</b>
<br>
<c:forTokens var="token" items="${tokens}" delims="," >
Found token: <c:out value="${token}" /><br>
</c:forTokens>
Ex: <c:forEach> with multiple delims
<%-- Tokenize using multiple delims --%>
<b>Tokenize the string "<c:out value="${tokens}" />" with delims= ",:#"</b>
<br>
<c:forTokens var="token" items="${tokens}" delims=",:#" >
Found token: <c:out value="${token}" /><br>
</c:forTokens>
Ex: Using Dynamic Values for the delims Attribute.
<c:forTokens var="token" items="${tokens}" delims="${param.delims}" >
Found token: <c:out value="${token}" /><br>
</c:forTokens>
7. URL-Related Actions
7.1) <c:import>
<c:import> is used to import, or include, the content of a URL-based resource. The resource itself can be relative, absolute, within the same context as, or in a foreign context to the requesting JSP.
Usage : <c:import url="/abc.html"/>
Ex: <c:import url="/hotoffthepress.html" var="hotoffthepress"
scope="session" context="/newreleases" />
----------------------
7.2) <c:url>
When using <c:url>, a URL can be built with the correct encoding and rewriting rules applied.
Ex: <c:url value="/MK/order" var="orderUrl"/>
<a href=‘<c:out value="${orderUrl}"/>’>Place an order</a>
Ex: Using <c:url> with <c:param> to Build Dynamic Links
<c:forEach var="selection" begin="1" end="${totalSize - 1}" step="${chunkSize}">
<a href="
<c:url value="/pagingdemoURL.jsp">
<c:param name="start" value="${selection}" />
</c:url>"
>
<b>(<c:out value="${selection}"/>
<c:out value="${selection + chunkSize - 1}"/>)
</b>
</a>
</c:forEach>
Ex: <c:url> with a Scoped Variable
<c:url var="homePage" scope="session" value="http://www.switchbacksoftware.com" />
Displaying a URL link by using a scoped variable
<p>
<a href="<c:out value="${homePage}" />">Home page</a>
-------------------------------
7.3) <c:param>
<c:param> action is used to add request parameters to a URL. It can be a nested action of <c:import>, <c:url>, and <c:redirect>.
Ex:
<c:url value="/mk/order" var=" orderUrl">
<c:param name="title" value="${param.title}"/>
<c:param name="isbn"/>
${param.isbn}
</c:param>
</c:url
------------------------
7.4) <c:redirect>
This action sends an HTTP redirect response to the client and aborts the processing of the page.
Ex: <c:redirect url="/booklist.html" context="/newreleases" />
-----------------------------------------------------------------------------------------------
XML Actions
The XML tag library brings us to actions that deal with XML manipulations.
1. eXtenstible Stylesheet Language (XSL)
- XSL is the stylesheet language of XML.
- XSL provides a comprehensive model and a vocabulary for writing such stylesheets using XML syntax.
- XSL is a language that can transform XML into HTML.
- XSL is also a method for defining XML parts and patterns that can then be used for sorting and filtering XML data.
- XSL can be used for formatting XML documents.
2. XSL Languages
XSL actually consists of three languages: XSLT, XPath, and XSL Formatting Objects (sometimes called XSLFO). XPath is a language to define XML parts or patterns. XSLT is a language for transforming XML documents into other types of documents or into other XML documents. XSL uses XSLT to take an XML source tree (or source document) and transform it into a results tree (or results document).
3. XML Path Language (XPath)
- XPath, one of the major elements of XSLT and a W3C recommendation.
- It is a set of syntax rules for defining parts of an XML document.
- XPath uses path expressions to make it possible to locate specific nodes within an XML document.
- Expressions look a lot like how we access traditional file paths.
Ex: XML Document
<?xml version="1.0" encoding="ISO-8859-1"?>
<catalog>
<book edition="1" >
<title>JSTL</title>
<author>Sue Spielman</author>
</book>
<catalog>
we could access the title by using the XPath expression " /catalog/book/title " . XPath is a language for addressing parts of an XML document.
4. Library Functions
There is a library of standard functions available in XPath for working with strings, numbers, and booleans. XPath supports numerical, equality, relational, and Boolean expressions. Expressions can be used to access nodes, sets of nodes, and attributes.
4.1) XPath node set functions
Method name Description
count Returns the number of selected elements
id Selects elements by their unique ID
last Returns a number equal to the context size from the expression evaluation context
local-name Returns the local part of the expanded-name of the node in the argument node-set that is first in document order
name Returns the name of an element
namespace-uri Returns the namespace URI of the expanded-name of the node in the argument node-set that is first in document order
position Returns a number equal to the context position from the expression evaluation context
4.2) XPath string functions
Method name Description
concat Returns the concatenation of its arguments
contains Returns true if the first string contains the second string, otherwise it returns false
normalize-space Removes leading and trailing spaces from a string
starts-with Returns true if the first string starts with the second string, otherwise it returns false
string Converts an object to a string
string-length Returns the number of characters in a string
substring Returns a substring
substring-after Returns a substring after a substring
substring-before Returns a substring before a substring
translate Translates letters in a string
4.3) XPath number functions
Method name Description
ceiling Returns the smallest integer that is not less than the argument
floor Returns the largest integer that is not greater than the argument
number Converts its argument to a number
round Returns the integer that is closest to the argument
sum Returns the sum, for each node in the argument node-set, of the result of converting the string-values of the node to a number
4.4) XPath Boolean functions
Method name Description
boolean Converts its argument to Boolean
false Returns false
lang Returns true or false depending on whether the language of the context node as specified by xml:lang attributes is the same as or is a sublanguage of the language specified by the argument string
not Returns true if its argument is false, and false otherwise
true Returns true
----------------------------------------------
XML LIBRARY
<%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>
5. Using the Select Attribute
- All of the XML actions of JSTL allow a way to specify XPath expressions.
- This is accomplished by using the select attribute.
- The select attribute is always specified as a string literal that is evaluated by the XPath engine.
Ex: <x:out select=“$catalog/book/title”/>
6. Accessing Resources
This is done by importing resources using the Core URL action <c:import> . The resource can then be used by such XML actions as <x:parse> and <x:transform> .
Ex: <c:import url="http://www.mkp.com/book?id=12345" var="xml"/>
<x:parse xml="${xml}" var="doc"/>
7. Node Types
- XML trees contain nodes. A node is one of seven types: root, element, text, attribute, namespace, processing instruction, or comment.
- The root node is the root of the tree.
- There is only one per tree.
- The root node can have element, processing instruction, and comment nodes.
A LocationPath is used to describe the type of node and where it can be found. For example:
child::* selects all element children of the context node.
child::node() selects all the children of the context node, whatever their node type.
There are two kinds of location paths: relative location paths and absolute location paths.
8. Parsing XML Documents
- The <x:parse> action is used to parse an XML document.
- The resulting object is then saved into a scoped variable as defined by either the var or the varDom attribute.
- The varDom attribute is a String that holds the name of the scoped variable.
Ex: <c:import url="http://www.mkp.com/catalog.xml" var="xml"/>
<x:parse source="${xml}" var="doc"/>
<x:out select="$doc/catalog/book/title"/>
Ex: <c:import var="xmlfile" url="/people.xml" />
<x:parse var="doc" xml="${xmlfile}" />
Hello <x:out select="$doc/person/firstname" />
OR
<x:parse var="doc" >
<c:import url="/people.xml" />
</x:parse>
9. Using <x:out> and <x:set>
- They look exactly like the ones on the Core Tag Library.
- The only difference is that instead of using the EL for the various Core actions, we use XPath to specify variables and content in the select attribute.
9.1) <x:out> Action
- The <x:out> action provides the same functionality as the Core <c:out> action.
- It allows for an XPath expression to be evaluated and then outputs the result of the evaluation to the current JspWriter object.
Ex: <x:out select="$doc/catalog/book/title"/>
9.2) <x:set> Action
- This action evaluates an XPath expression and then saves the result into a scoped variable as defined by the var attribute.
- In addition to the var and scope attributes, the <x:set> also has the select attribute for defining the XPath expression.
Ex: <x:set var="bookTitle" scope="request" select="$doc/catalog/book/title"/>
Ex: Using XPath with <x:set> and <x:out>
people.xml
<person>
<firstname>Sue</firstname>
<lastname>Spielman</lastname>
</person>
<c:import var="xmlfile" url="/people.xml" />
<x:parse var="doc" xml="${xmlfile}" />
Hello <x:out select="$doc/person/firstname" />
<x:set var="name" select="$doc/person" scope="request" />
Print out lastname from a subset of the person.xml document : <x:out select="$name/lastname" />
10. Using XML Documents to Determine Flow Control
The actions available are:
<x:if>
<x:choose>
<x:when>
<x:otherwise>
<x:forEach>
Ex: catalog.xml File
<catalog publisher="MK">
<book>
<title>JSTL</title>
<author>Sue Spielman</author>
<edition>1</edition>
</book>
<book>
<title>Struts</title>
<author>Sue Spielman</author>
<edition>2</edition>
</book>
<book>
<title>Java</title>
<author>Sikora</author>
<edition>1</edition>
</book>
</catalog>
Ex: Using <x:if> for Control Flow
1) <c:set var="publisher" value="MK" />
<c:import var="xmlfile" url="/catalog.xml" />
<x:parse var="doc" xml="${xmlfile}" />
<x:if select="$doc/catalog[@publisher=$pageScope:publisher]">
Welcome to the <c:out value="${publisher}" /> book catalog.
</x:if>
2) <x:if select="$doc/catalog/book/[title=‘JSTL’]">
You’ve made a fine choice!
</x:if>
Ex: <x:choose>, <x:when>, <x:otherwise> in Action
<x:choose>
<x:when select="$doc/catalog/book/edition=1">
The book <x:out select="$doc/catalog/book/title" /> is in its first edition.
</x:when>
<x:when select="$doc/catalog/book/edition=2">
The book <x:out select="$doc/catalog/book/title" /> is in its second edition.
</x:when>
<x:otherwise>
The book <x:out select="$doc/catalog/book/title" /> is a best seller in its third edition!
</x:otherwise>
</x:choose>
Ex: <x:forEach> Processing
<c:import var="xmlfile" url="/catalog.xml" />
<x:parse var="doc" xml="${xmlfile}" />
<table><tr><th>Title</th><th>Author</th><th>Edition</th></tr>
<x:forEach select="$doc//book">
<tr>
<td><x:out select="title" /></td>
<td><x:out select="author" /></td>
<td><x:out select="edition" /></td>
</tr>
</x:forEach>
</table>
Nested forEach Loops
Ex: catalog.xml File for Nested Iterations
<catalogs>
<catalog publisher="MK">
<book>
<title>JSTL</title>
<author>Sue Spielman</author>
<edition>1</edition>
</book>
<book>
<title>Struts</title>
<author>Sue Spielman</author>
<edition>2</edition>
</book>
<book>
<title>Java</title>
<author>Sikora</author>
<edition>1</edition>
</book>
</catalog>
<catalog publisher="New Age Books">
<book>
<title>Learning Ashtanga Yoga</title>
<author>Sri K. Pattabhi Jois</author>
<edition>1</edition>
</book>
</catalog>
</catalogs>
Using Nested <x:forEach>
<x:forEach select="$doc//catalog">
<h2>Catalog listing for <x:out select="@publisher" />
<table><tr><th>Title</th><th>Author</th><th>Edition</th></tr>
<x:forEach select="book">
<tr>
<td><x:out select="title" /></td>
<td><x:out select="author" /></td>
<td><x:out select="edition" /></td>
</tr>
</x:forEach>
</table>
</x:forEach>
11. XML Transformation Actions
The XML transformation actions provide a mechanism for page authors to use XSLT stylesheets. XSL is the eXtensible Stylesheet Language and is used for expressing style sheets.
Ex:
<c:import url="http://www.mkp.com/catalog" var="xml"/>
<c:import url="/WEB-INF/xslt/catalogList.xsl" var="xslt"/>
<x:transform xml="${xml}" xslt="${xslt}"/>
Ex:XSL File to Use for Transformation
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<h2>Using an XSL stylesheet to transform an XML file</h2>
<table border="1">
<tr bgcolor="#FF00FF">
<th align="left">Title</th>
<th align="left">Author</th>
<th align="left">Edition</th>
</tr>
<xsl:for-each select="catalogs/catalog/book">
<tr>
<td><xsl:value-of select="title"/></td>
<td><xsl:value-of select="author"/></td>
<td><xsl:value-of select="edition"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
JSP Part
<c:import var="xmlfile" url="/catalog.xml" />
<c:import var="xslfile" url="/catalog.xsl" />
<x:parse var="doc" xml="${xmlfile}" />
<x:transform xml="${xmlfile}" xslt="${xslfile}" />
--------------------------------------------------------------------------------------
SQL Tag Library
The JSTL includes a number of actions that provide a mechanism for interacting with databases.
The JSTL SQL actions provide functionality that allows for:
■ Making database queries
■ Accessing query results
■ Performing database modifications
■ Database transactions
Usage : <%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>
1. The Available <SQL> Actions
There are six actions provided in this tag library:
■ <sql:setDataSource> for exporting a variable that defines a data source
■ <sql:query> for querying to the database
■ <sql:update> for updating the database
■ <sql:transaction> for establishing a transaction context for doing queries and updates
■ <sql:param> for setting parameter markers (“?”) used in SQL statements.
■ <sql:dateParam> for setting parameter markers (“?”) of type java.util.Date in SQL statements.
2. Working with the Data Source
SQL actions operate on a data source. A data source is an implementation of the javax.sql.DataSource interface and allows for the retrieval of a connection, or connections, to a specific database or data source.
2.1) <sql:setDataSource>
The <sql:setDataSource> is used to export a data source either as a scoped variable or as the javax.servlet.jsp.jstl.sql.dataSource data source configuration variable. The data source may be specified by using the dataSource attribute. It is also possible to specify the data source by using the four JDBC parameter attributes. All four of the parameters are just String types. These attributes are driver, url, user, and password.
Ex: Setting a Data Source
<sql:setDataSource var="datasource"
driver="org.gjt.mm.mysql.driver"
url="jdbc:mysql://localhost/db"
user="guest"
password="guest"/>
<sql:query datasource="${datasource}" ... />
Ex: Setting the Data Source in the web.xml
<context-param>
<param-name>javax.servlet.jsp.jstl.sql.dataSource
</param-name>
<param-value>
jdbc:mysql://localhost/jstlbook,org.gjt.mm.mysql.Driver
</param-value>
</context-param>
3. Configuring a Data Source
There are two ways that a data source can be configured: through an attribute or through a configuration setting. Using the dataSource attribute of the SQL actions, it is possible to explicitly configure the data source for the action.
If all SQL actions are going to use the same data source, it is more convenient to set the data source by using the configuration setting javax.servlet.jsp.jstl.sql.dataSource. The constant Config.SQL_DATA_SOURCE can be used to refer to this configuration setting. The dataSource can be specified as either a String or javax.sql.DataSource. When using the configuration setting, there are two ways a data source can be specified as a string. The first way is through a JNDI relative path, assuming a container supporting JNDI. For example, with the absolute JNDI resource path java:comp/env/jdbc/myDatabase, the JNDI relative path to the data source resource would simply be jdbc/myDatabase, given that java:comp/env is the standard JNDI root for a J2EE application. The second way is by specifying the parameters needed by the JDBC Driver Manager class, using the syntax url[,[driver][,[user][,password]]]. For example, jdbc:mysql://localhost/,org.gjt.mm.mysql.Driver
4. Using a Data Source
The actions that use the data source to access a database are the <sql:query>, <sql:update>, and <sql:transaction>.
Ex: Setting and Using a Data Source with <sql:setDataSource>
<sql:setDataSource var="datasource"
scope="application"
driver="org.gjt.mm.mysql.Driver"
url="jdbc:mysql://localhost/jstlbook"/>
<sql:update dataSource="${datasource}"
sql="
CREATE TABLE IF NOT EXISTS books (
title VARCHAR(75),author VARCHAR(25),
edition INTEGER,pubdate TIMESTAMP(8))">
</sql:update>
4.1) <sql:update> Action
The <sql:update> action is used to execute SQL insert, update, or delete statements. It is also possible to perform a SQL statement that returns nothing, like a DDL statement. The SQL statement can be specified either by using the sql attribute or by providing the statement in the action’s body content.
Ex: Using <sql:update>
<sql:update dataSource="$(datasource)" var="updateResult"
scope="request">
UPDATE book SET Title = ‘JSTL First Edition’ WHERE author = ‘Spielman’
</sql:update>
Ex: Inserting Data Using var
<sql:update var="result"
sql="INSERT INTO books (title, author,
edition, pubdate) values(‘JSTL: Practical Guide for JavaProgrammers’
,‘Spielman’,1,‘12/1/03’)">
</sql:update>
<c:if test="${result == 1}" >
Your data was inserted successfully!
</c:if>
4.2) <sql:query>
The <sql:update> allows you to make updates, but sometimes you just want to get data. The <sql:query> action takes care of this for you.
Ex: Setting maxRows in web.xml
<context-param>
<param-name>javax.servlet.jsp.jstl.sql.maxRows</param-name>
<param-value>100</param-value>
</context-param>
Ex: Combining maxRows and startRow
<sql:query var="bookList" dataSource="${datasource}"
maxRows="5" startRow="1">
SELECT * FROM books WHERE title LIKE ‘J%’ ORDER BY author
</sql:query>
Ex: SQL Defined in Attribute
<sql:query sql="SELECT * FROM books WHERE title = ‘JSTL’ ORDER BY author"
var="titles"
dataSource="${datasource}" >
</sql:query>
Ex: SQL in Body Content
<sql:query var="titles" dataSource="${datasource}" >
SELECT * FROM books WHERE title = ‘JSTL’ ORDER BY author
</sql:query>
4.3) Passing Parameters to SQL Statements
JSTL handles this with the <sql:param> action. <sql:param> can be nested in a <sql:update> or a <sql:query> action. A query can contain parameter markers. These markers are indicated by using a “?” in the query.
Ex: Supply a Parameter in a Query
<sql:query sql="SELECT * FROM books WHERE title = ? ORDER BY author"
var="titles"
dataSource="${datasource}" >
<sql:param value="${titleSelected}"/>
</sql:query>
Ex: Query Using maxRows and startRow
<sql:query sql="SELECT * FROM books WHERE title = ‘JSTL’ ORDER BY
author" var="titles"
dataSource="${datasource}"
maxRows="5"
startRow="7" >
</sql:query>
Ex: Search Example
Search.html
<form action="doquery.jsp" method="post">
<table><tr>
<td>book title:<td>
<td><input type="text" name="title" value="" />
</td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Perform Search" /></td>
</tr>
</table></form>
doquery.jsp Source
<c:catch var="sqlError">
<sql:query var="bookList" >
SELECT * FROM books WHERE title LIKE ? ORDER BY author
<sql:param value="${param.title}" />
</sql:query>
</c:catch>
<c:choose>
<c:when test="${not empty sqlError}" >
A SQL error has occurred.
</c:when>
<c:otherwise>
<h2>Listing all books that start with <c:out value="${param.title}" />, ordered by author</h2>
<br>
<c:if test="${bookList.rowCount == 0}" >
<c:out value="No matches found" />
</c:if>
<table>
<th>Title</th>
<th>Author</th>
<c:forEach var="book" items="${bookList.rows}">
<tr>
<td><c:out value="${book.title}" /></td>
<td><c:out value="${book.author}" /></td>
</tr>
</c:forEach>
</table>
</c:otherwise>
</c:choose>
Ex: Using the <sql:dateParam> in a Query
<sql:query var="bookList" >
SELECT * FROM books WHERE title LIKE ? AND pubdate > ? ORDER BY author
<sql:param value="${param.title}" />
<sql:dateParam value="${param.pubdate}" />
</sql:query>
4.4) Accessing Rows and Columns
Ex: Getting at the Row Data Using the Rows Collection
<table>
<tr>
<th>Title</th>
<th>Author</th>
<th>Publication Date</th>
</tr>
<c:forEach var="book" items="${bookList.rows}">
<tr>
<td><c:out value="${book.title}" /></td>
<td><c:out value="${book.author}" /></td>
<td><fmt:formatDate value="${book.pubdate}" type="date"/></td>
</tr>
</c:forEach>
</table>
Ex: Getting at the Row Data Using the columnNames and rowsByIndex Collection
<table>
<tr>
<c:forEach items="${bookList.columnNames}" var="columnName">
<th><c:out value="${columnName}"/></th>
</c:forEach>
</tr>
<c:forEach var="book" items="${bookList.rowsByIndex}">
<tr>
<c:forEach var="columnValue" items="${book}" >
<td><c:out value="${columnValue}"/></td>
</c:forEach>
</tr>
</c:forEach>
</table>
5. JSTL SQL <sql:transaction> Tag
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.
Ex:
Step 1:
Create the table Employee in TEST database as follows:
mysql> use TEST;
mysql> create table Students
(
id int not null,
first varchar (255),
last varchar (255),
dob date
);
Create Data Records
mysql> INSERT INTO Students
VALUES (100, 'Zara', 'Ali', '2002/05/16');
mysql> INSERT INTO Students
VALUES (101, 'Mahnaz', 'Fatma', '1978/11/28');
mysql> INSERT INTO Students
VALUES (102, 'Zaid', 'Khan', '1980/10/10');
mysql> INSERT INTO Students
VALUES (103, 'Sumit', 'Mittal', '1971/05/08');
Now let us write a JSP which will make use of <sql:update> along with <sql:transaction> to execute a SQL UPDATE statement. Here code inside <sql:transaction> either would be exeucted completely or not at all:
<%@ page import="java.io.*,java.util.*,java.sql.*"%>
<%@ page import="javax.servlet.http.*,javax.servlet.*"%>
<%@ page import="java.util.Date,java.text.*" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
<html>
<head>
<title>JSTL sql:transaction Tag</title>
</head>
<body>
<sql:setDataSource var="snapshot" driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost/TEST"
user="root" password="cohondob"/>
<%
Date DoB = new Date("2001/12/16");
int studentId = 100;
%>
<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>
<table border="1" width="100%">
<tr>
<th>Emp ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>DoB</th>
</tr>
<c:forEach var="row" items="${result.rows}">
<tr>
<td><c:out value="${row.id}"/></td>
<td><c:out value="${row.first}"/></td>
<td><c:out value="${row.last}"/></td>
<td><c:out value="${row.dob}"/></td>
</tr>
</c:forEach>
</table>
</body>
</html>
--------------------------------------------------------------------------------------------
JSTL Functions:
JSTL includes a number of standard functions, most of which are common string manipulation functions. Following is the syntax to include JSTL Functions library in your JSP:
<%@ taglib prefix="fn"
uri="http://java.sun.com/jsp/jstl/functions" %>
------------------
1. JSTL fn:contains() Function
The fn:contains() function determines whether an input string contains a specified substring.
Syntax:
The fn:contains() function has following syntax:
boolean contains(java.lang.String, java.lang.String)
Example:
Following is the example to explain the functionality of this function:
<c:set var="theString" value="I am a test String"/>
<c:if test="${fn:contains(theString, 'test')}">
<p>Found test string<p>
</c:if>
<c:if test="${fn:contains(theString, 'TEST')}">
<p>Found TEST string<p>
</c:if>
----------------
2. JSTL fn:containsIgnoreCase() Function
The fn:containsIgnoreCase() function determines whether an input string contains a specified substring. While doing search it ignores the case.
Syntax:
The fn:containsIgnoreCase() function has following syntax:
boolean containsIgnoreCase(java.lang.String, java.lang.String)
Example:
<c:set var="theString" value="I am a test String"/>
<c:if test="${fn:containsIgnoreCase(theString, 'test')}">
<p>Found test string<p>
</c:if>
<c:if test="${fn:containsIgnoreCase(theString, 'TEST')}">
<p>Found TEST string<p>
</c:if>
-------------
3. JSTL fn:endsWith() Function
The fn:endsWith() function determines whether an input string ends with a specified suffix.
Syntax:
The fn:endsWith() function has following syntax:
boolean endsWith(java.lang.String, java.lang.String)
Example:
<c:set var="theString" value="I am a test String 123"/>
<c:if test="${fn:endsWith(theString, '123')}">
<p>String ends with 123<p>
</c:if>
<c:if test="${fn:endsWith(theString, 'TEST')}">
<p>String ends with TEST<p>
</c:if>
-------------
4. JSTL fn:escapeXml() Function
The fn:escapeXml() function escapes characters that can be interpreted as XML markup.
Syntax:
The fn:escapeXml() function has following syntax:
java.lang.String escapeXml(java.lang.String)
Example:
<c:set var="string1" value="This is first String."/>
<c:set var="string2" value="This <abc>is second String.</abc>"/>
<p>With escapeXml() Function:</p>
<p>string (1) : ${fn:escapeXml(string1)}</p>
<p>string (2) : ${fn:escapeXml(string2)}</p>
------------
5. JSTL fn:indexOf() Function
The fn:indexOf() function returns the index within a string of a specified substring.
Syntax:
The fn:indexOf() function has following syntax:
int indexOf(java.lang.String, java.lang.String)
Example:
<c:set var="string1" value="This is first String."/>
<c:set var="string2" value="This <abc>is second String.</abc>"/>
<p>Index (1) : ${fn:indexOf(string1, "first")}</p>
<p>Index (2) : ${fn:indexOf(string2, "second")}</p>
----------
6. JSTL fn:join() Function
The fn:join() function concatenates all the elements of an array into a string with a specified separator.
Syntax:
The fn:join() function has following syntax:
String join (java.lang.String[], java.lang.String)
Example:
<c:set var="string1" value="This is first String."/>
<c:set var="string2" value="${fn:split(string1, ' ')}" />
<c:set var="string3" value="${fn:join(string2, '-')}" />
<p>Final String : ${string3}</p>
----------
7. JSTL fn:length() Function
The fn:length() function returns the string length or the number of items in a collection.
Syntax:
The fn:length() function has following syntax:
int length(java.lang.Object)
Example:
<c:set var="string1" value="This is first String."/>
<c:set var="string2" value="This is second String." />
<p>Length of String (1) : ${fn:length(string1)}</p>
<p>Length of String (2) : ${fn:length(string2)}</p>
---------
8.JSTL fn:replace() Function
The fn:replace() function replaces all occurrences of a string with another string.
Syntax:
The fn:replace () function has following syntax:
boolean replace(java.lang.String, java.lang.String, java.lang.String)
Example:
<c:set var="string1" value="This is first String."/>
<c:set var="string2" value="${fn:replace(string1,
'first', 'second')}" />
<p>Final String : ${string2}</p>
----------
9. JSTL fn:split() Function
The fn:split() function splits a string into an array of substrings based on a delimiter string.
Syntax:
The fn:split() function has following syntax:
java.lang.String[] split(java.lang.String, java.lang.String)
Example:
<c:set var="string1" value="This is first String."/>
<c:set var="string2" value="${fn:split(string1, ' ')}" />
<c:set var="string3" value="${fn:join(string2, '-')}" />
<p>String (3) : ${string3}</p>
<c:set var="string4" value="${fn:split(string3, '-')}" />
<c:set var="string5" value="${fn:join(string4, ' ')}" />
<p>String (5) : ${string5}</p>
------------
10. JSTL fn:startsWith() Function
The fn:startsWith() function determines whether an input string starts with a specified substring.
Syntax:
The fn:startsWith() function has following syntax:
boolean startsWith(java.lang.String, java.lang.String)
Example:
<c:set var="string" value="Second: This is first String."/>
<c:if test="${fn:startsWith(string, 'First')}">
<p>String starts with First</p>
</c:if>
<br />
<c:if test="${fn:startsWith(string, 'Second')}">
<p>String starts with Second</p>
</c:if>
------------
11. JSTL fn:substring() Function
The fn:substring() function returns a subset of a string specified by start and end indices.
Syntax:
The fn:substring () function has following syntax:
java.lang.String substring(java.lang.String, int, int)
Example:
<c:set var="string1" value="This is first String."/>
<c:set var="string2" value="${fn:substring(string1, 5, 15)}" />
<p>Final sub string : ${string2}</p>
----------
12. JSTL fn:substringAfter() Function
The fn:substringAfter() function returns the part of a string after a specified substring.
Syntax:
The fn:substringAfter() function has following syntax:
java.lang.String substringAfter(java.lang.String, java.lang.String)
Example:
<c:set var="string1" value="This is first String."/>
<c:set var="string2" value="${fn:substringAfter(string1, 'is')}" />
<p>Final sub string : ${string2}</p>
-----------
13. JSTL fn:substringBefore() Function
The fn:substringBefore() function returns the part of a string before a specified substring.
Syntax:
The fn:substringBefore() function has following syntax:
java.lang.String substringBefore(java.lang.String,
java.lang.String)
Example:
<c:set var="string1" value="This is first String."/>
<c:set var="string2" value="${fn:substringBefore(string1,
'first')}" />
<p>Final sub string : ${string2}</p>
----------
14. JSTL fn:toLowerCase() Function
The fn:toLowerCase() function converts all the characters of a string to lowercase.
Syntax:
The fn:toLowerCase() function has following syntax:
java.lang.String toLowerCase(java.lang.String)
Example:
<c:set var="string1" value="This is first String."/>
<c:set var="string2" value="${fn:toLowerCase(string1)}" />
<p>Final string : ${string2}</p>
--------
15. JSTL fn:toUpperCase() Function
The fn:toUpperCase() function converts all the characters of a string to uppercase.
Syntax:
The fn:toUpperCase() function has following syntax:
java.lang.String toLowerCase(java.lang.String)
Example:
<c:set var="string1" value="This is first String."/>
<c:set var="string2" value="${fn:toUpperCase(string1)}" />
<p>Final string : ${string2}</p>
-----------
16. JSTL fn:trim() Function
The fn:trim() function removes white space from both ends of a string.
Syntax:
The fn:trim() function has following syntax:
java.lang.String trim(java.lang.String)
Example:
<c:set var="string1" value="This is first String "/>
<p>String (1) Length : ${fn:length(string1)}</p>
<c:set var="string2" value="${fn:trim(string1)}" />
<p>String (2) Length : ${fn:length(string2)}</p>
<p>Final string : ${string2}</p>
------------------------------------------------------------------------------------------------------------------
No comments:
Post a Comment