Sei sulla pagina 1di 64

Introduction to JSTL

(JSP Standard Tag Library)

As J2EE programmers, we are familiar with Servlets , JSP and JavaBeans. Any JSP page should encapsulate the business logic in a bean and invoke it by using <jsp:useBean> tag. Till recently, a combination of Servlets, JSP and beans was the standard practice. But, the JCP released an API for enabling programmers to create custom tags and use them in their JSP pages. The difference between javabean and java custom tags was that, though both made use of java classes, tags can be used by non-programmers also without knowledge of Java programming, just as they would use html tags.( From a programmer's perspective,however, a much more important distinction is that tags are specific to the page in which they are created while javabeans are general. )

Java, JSP, and JSTL

// greeting.htm =============
<html> <body>

<form method=post action= 'http://localhost:8080/servlet/greeting'> <input type=text name='text1'> <input type=submit> </form> </body> </html>

(relevant section of greeting.java servlet) // greeting.java ( code-snippet only) public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException,IOException { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); //------------------------------String s = req.getParameter("text1"); out.println("<html><body bgcolor=yellow>"); out.println("we welcome"+",<br>"); out.println (s); out.println("</body> </html>"); }

// greeting1.jsp <html> <body bgcolor=yellow> <% String s = request.getParameter("text1"); out.println("we welcome"+<br>); out.println(s); %> </body> </html>

---------------------------------------------// greeting2.jsp <html> <body bgcolor=yellow> we welcome <br> <%= request.getParameter("text1") %> </body> </html>

// greeter.java //============== package ourbeans; public class greeter { public greeter() { } public String greetme(String s) return "we welcome..."+s; } }

/ greeting3.jsp <html> <body> <jsp:useBean id='bean1' class='ourbeans.greeter'> <% String s = request.getParameter ("text1"); String r = bean1.greeteme(s); out.println(r); %> </body> </html>

// greeting4.jsp ( uses JSTL) =========== <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <body> <c:set var=s value="${param.text1}" /> We welcome<br> <c:out value="${s}" /> </body> </html>

There are five groups under which the JSTL tags have been organized. They are as follows: 1) core 2) xml 3) sql 4) formatting 5) functions.

JSTL and other frameworks


JSTL works with JSP versions 1.2 and higher. JSTL inherits all the benefits from JSP JSTL will be useful to you whether you use Struts, JavaServer Faces, a different framework, or nothing.

JSTL A Template System


Web browsers dont care how web pages are produced. To a web browser, it makes no difference whether the page its displaying is static (unchanging) or dynamic (produced by a programming language or template system) Template systems like JSP and JSTL are similar to a word-processing feature called mail merge.

In a web template system, template text is mixed with a number of placeholders. These placeholders are filled in every time the page needs to respond to a web request.

JSP Tags

An interesting subtlety about JSP tags and HTML tags is worth highlighting:

You can use JSP tags inside HTML tags, because these HTML tags are just arbitrary template text. For instance, you can write:

<a href="<tag:one/>">
If <tag:one>s purpose is to print a URL, then this tag might be replaced with <a href="http://your/url "> and it works fine

However, JSP tags cannot appear inside another JSP tags attributes. For instance, if <tag:one> and <tag:two> are both JSP tags, then you cant write

<tag:one attribute="<tag:two/>"/>

Standard JSP Tags


Some JSP tags are built into JSP; theyre effectively hard-wired into the JSP standard. These tags are often called standard tags, although the term is somewhat confusing. This group of standard tags doesnt include JSTL tags; instead, it includes core JSP tags that predate JSTL by several years. JSTLs tags are also standard, but they fall into a separate group of tags

Standard JSP Tags

Standard JSP Tags

<jsp:include>

Lets you include one JSP page from within another, including the static content Always looks for files on the local server Ignores the htmls <base> tag

<jsp:forward> <jsp:useBean>

Other related tags

JSP Directives

Directives are pseudo-tags that have special meaning to the container;


they are not passed through to the browser but, instead, are processed by the JSP engine <%@ include %> directive <%@ page %> directive <%@ taglib %> directive

<%@ include %> directive

e.g., <%@ include file="b.jsp" %> Different from <jsp:include> <%@ include %> directive works by finding the target file and inserting it into your JSP page, just as if you had cut and pasted it using a text editor. By contrast, <jsp:include> locates the target page while your JSP page is executing. When page A uses <%@ include %> to include page B, page Bs data is simply included in page A every time it is compiled

<jsp:include> vs. <%@ include%>

If a file included with <%@ include %> changes, its changes will not be noticed until the page containing the directive also changes

<%@ include %> cannot work with Servlets <%@ include %> is more efficient than <jsp:include>, but it also uses much more disk space when large files are included. With <jsp:include>, the two pages involved are two entirely separate pages

page A must be changedand recompiled for any changes in B to take effect <jsp:include> notices changes immediately

They can use the same names for different variables, or they can use different prefixes for the same tag library With <%@ include %>, because page A and page B are essentially merged before being compiled, there might be clashes between names within the two pages

<%@ page %> directive


<%@ page %>, lets you modify some properties of a JSP page This directives goal is to provide metainformation about how to process the page

JSP tag libraries

In contrast with the core JSP tags, other tags can be provided by you, vendors - and, of course, JSTL. Such tags come in packages called tag libraries

groups of individual tags that are usually designed to work together, or at least to serve a common function.

JSTL is a collection of such tag libraries. JSTL is distinguished by being the standard tag library

the one that is found everywhere, and the one you can learn once and reuse wherever JSP containers are found.

The <%@ taglib %> directive

Tag libraries use prefixes other than jsp, and they must be explicitly imported into pages before they can be used. Thus, whereas the jsp: tags can be used in any JSP page without fanfare or preparation, you need to introduce others (including JSTLs) using a special pseudo-tag known as a directive. Think of JSP directives as being somewhat like the HTML <head> tag

their function is not specifically to display anything in the browser, but instead to describe some information about the page itself.

The <%@ taglib %> directive


Directives are one JSP feature that doesnt strictly follow an XML-like syntax. Instead, a directive begins with <%@ and ends with %>. One such directive, <%@ taglib %>, is used to import a tag library into a page. Even though they begin with <%@ and end with %>, directives are similar to XML tags in that they accept attributes. The <%@ taglib %> directive requires two attributes: uri and prefix.

Tag Libraries - URI

Every tag library has something called a Universal Resource Identifier (URI) associated with it.

It simply acts as a way of differentiating one tag library from another To use a tag library in a JSP page, you should know its URI Can be obtained from the author or provider of the library. If you use JSTL, then the JSTL specification will tell you the appropriate URIs for the JSTL libraries.

Not used to load anything over the Web.

Tag Libraries - URI and Prefix

Knowing a librarys URI or file path, you can use the <%@ taglib %> directive to register it and, at the same time, assign it an XML-like namespace prefix for use within the page.

<%@ taglib uri="http://www.acme.com/ custom.tld" prefix="acme" %> Imports the tag library identified by the URI http://www.acme.com/custom.tld into the page, using the prefix acme. After this directive appears in a page, tags from the library can be used with the acme prefix. <acme:create>

JSTLs tag libraries


JSTL is provided as a collection of tag libraries designed to meet particular needs. JSTL includes the libraries and recommends certain prefixes JSTL divides its tags into four groups and makes them available as separate tag libraries.

Core library XML processing library Internationalization (i18n) & formatting Database (SQL) access

Core Library

The core library includes tags for the following uses:


Accessing and modifying data in memory Making decisions in your pages Looping over data

Suggested Prefix: c URI: http://java.sun.com/jstl/core Example: <c:forEach>

XML processing library

The XML library includes tags for the following purposes:


Parsing (that is, reading) XML documents Printing parts of XML documents Making decisions in your page based on the contents of an XML document

Suggested Prefix: x URI: http://java.sun.com/jstl/jstl/xml Example: <x:forEach>

Internationalization (i18n) & formatting

The formatting and internationalization library includes tags for these uses:

Reading and printing numbers Reading and printing dates (with support for time zones) Helping your application work with more than one language

Suggested Prefix: fmt URI: http://java.sun.com/jstl/jstl/fmt Example: <fmt:formatDate>

Database (SQL) access


The SQL library helps you read and write data from databases. Suggested Prefix: sql URI: http://java.sun.com/jstl/jstl/sql Example: <sql:query>

Using JSTL in your pages


Before you can use a tag library, you need to import it. For each page, you only need to import the libraries you actually use Core

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

XML

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


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

Formatting

Database

JSTL Tag Libraries


JSTL uses a simple language called an expression language to make it easy for you to access information Before JSTL, you really had to know Java to produce an effective JSP page JSTL makes writing pages easier. Its expression language is much simpler than Java; in fact, its even simpler than JavaScript.

Expressions and the <c:out> tag


The most fundamental tag

used more often than any other tag in JSTL

Prints the result of an expression <c:out> tag is a little like JSPs and ASPs <%= %> <c:out value="Hi, there!"/>

prints the text, Hi there!

The <c:out> tag becomes useful only when the value attribute contains an expression in JSTLs expression language <c:out value="${1 + 2}"/>

JSTL Expressions

In JSTL 1.0, expressions have special meaning only inside JSTL tag attributes

<p>Hi ${username}</p> Prints as it is

JSTL expressions also have no special meaning inside an HTML tags attribute.

<a href="${link}"/> Meaning-less

<c:out > default attribute


<c:out value="${username}" default="Nobody"/> <c:out value="${username}">

Nobody

</c:out> <input type="text name="username value="<c:out value="${param.username}/>"/>

Accessing Data using JSTL


The major goal of the JSTL expression language is to make data easy to access. This data can fall into a number of categories

scoped variables, request parameters

Basic syntax to access scoped variables


In some ways, the JSTL expression language centers on scoped variables An expression like ${username} simply means the scoped variable named username. When the name of a scoped variable appears alone in an expression, the variable scope is searched in following sequence

page scope, request, session, application

Basic syntax to access scoped variables


${pageScope.username} ${requestScope.username} ${sessionScope.username} ${applicationScope.username} <c:out value="${sessionScope.user}"/>

JSTL tags also let you create and store scoped variables

Basic syntax to access scoped variables

${sessionScope.shoppingCart}

Such a variable refers to an entire collection of objects, organized under a single name: shoppingCart.

${sessionScope.shoppingCart[0]} ${sessionScope.user.name} <c:out value="${sessionScope. shoppingCart[1].price - 10}"/> ${sessionScope.user["name"]} is equivalent to ${sessionScope.user.name}

Request parameters and the expression language


<c:out value="${param.username}"/> <p>One language you can read is <c:out value="${param.language}"/></p>

Accessing other data with JSTL

Cookies

If youre told that a cookie called colorPreference is available, you can access it with an expression like ${cookie.colorPreference} Web browsers send information about their make and model to servers using a header called User-Agent

Headers

${header["User-Agent"]}

Initialization parameters

${initParam.headerUrl}.

Comparisons

You can use expression language to compare values

the expression ${2 == 2} results in true

Every comparison operator has a symbolic version (==) and a textual one (eq)

Expression Language

Checking to see if a variable exists

${empty param.choice} ${empty sessionScope.userName} <c:out value="Hi ${user.first} ${user.last}" />

Multiple Expressions

Saving data with <c:set>


Many JSTL tags let you create scoped variables; the most basic is <c:set> value

var

The expression to compute Required - No Default - Use body

scope

The name of the scoped variable to save Required - Yes Default - None The scope of the variable to save Required - No Default - page

<c:set>

<c:set var="four" value="${3 + 1}"/>

<c:set var="four" scope="session" value="${3 + 1}"/> <c:set var="eight"> <c:out value="${4 * 2}"/> </c:set>

This tag creates a page-scoped variable named eight and sets it to the string 8, which is the result of the <c:out> tag

Deleting data with <c:remove >


<c:remove var="do" scope="session"/> var

The name of the scoped variable to delete Required - Yes Default - None The scope of the variable to delete Required - No Default - Any

scope

JSTL Flow Control

JSTLs flow control comes in two forms:

Conditional logic, or conditions Looping, or iteration

JSTL Decisions
Yes-or-no conditions with <c:if> Mutually exclusive conditions with <c:choose>, <c:when>, and <c:otherwise>

Yes-or-no conditions with <c:if>

test

Condition to evaluate. If true, process the body; if false, ignore the body Required - Yes Default - None
Name of the attribute to expose a boolean value Required - No Default - None Scope of the attribute to expose a boolean value Required - No Default - page

var

scope

test attribute

The test attribute specifies a conditional expression to evaluate.

if the test expression evaluates to false, the page skips the body of the <c:if> tag. The body can contain any valid JSP code, including text, HTML tags, or other JSP tags
<c:if test="${user.education == doctorate}"> Dr. </c:if> <c:out value="${user.name}"/>

<c:if test="${user.education == doctorate}"> --do something </c:if>

<c:if>

<font size="2" <c:if test="${user.education == doctorate}"> color="red </c:if> > Hello</font> <c:if test="${error1}"> Error 1 has occurred </c:if> <c:if test="${error2}"> Error 2 has occurred </c:if> <c:if test="${error1 or error2}"> <c:if test="${error1}"> Error 1 has occurred </c:if> <c:if test="${error2}"> Error 2 has occurred </c:if> </c:if>

The var and scope attributes

<c:if test="${sessionScope.flags.errors.serious.error1}" var="error1"> -- Saves variable A serious error has occurred. </c:if> [ large page body ]

<c:if test="${error1}"> -- Uses variable Since a serious error occurred, your data has not been saved. </c:if>

Mutually exclusive conditions

The <c:choose> tag is simple:

it takes no attributes and serves only as a container for <c:when> and <c:otherwise> tags. Just as HTMLs <td> tag makes no sense outside a <table>, <c:when> and <c:otherwise> make no sense outside a <c:choose>

Mutually exclusive conditions

<c:choose> <c:when test="${error1}">Error 1 has occurred </c:when> <c:when test="${error2}">Error 2 has occurred </c:when> <c:when test="${error3}">Error 3 has occurred </c:when> </c:choose>

Only one of these <c:when> tags can succeed

<c:choose> <c:when test="${error1}">Error 1 has occurred </c:when> <c:when test="${error2}">Error 2 has occurred </c:when> <c:when test="${error3}">Error 3 has occurred </c:when> <c:otherwise>Everything is fine </c:otherwise> </c:choose>

Addition of <c:otherwise> to display the default message

JSTL Looping
General-purpose looping with <c:forEach> Iterating over strings with <c:forTokens>

General-purpose looping with <c:forEach>

The basic function of <c:forEach> is to consider every item in the collection specified by its items attribute. For each item in the collection, the body of the <c:forEach> tag will be processed once,

the current item is exposed as a page-scoped variable whose name is specified by <c:forEach>s var attribute.

<c:forEach items="${user.medicalConditions}" var="ailment"> <c:out value="${ailment}"/> </c:forEach>

Iterating over strings with <c:forTokens>


A token is a single, discrete unit within a larger string. The <c:forTokens> tag iterates over tokens, which it parses from an input string

<c:forTokens items="a;b;c;d" delims=";" var="current"> <c:out value="${current}"/> </c:forTokens>

Iterating over strings with <c:forTokens>

<c:forTokens items="a,b,c,d,e,f" delims="," var="letter begin="4"> <c:out value="${letter}"/> </c:forTokens> This invocation of the tag will print out only the letters e and f. Similarly, we can use only end:

<c:forTokens items="a,b,c,d,e,f" delims="," var="letter" end="4"> <c:out value="${letter}"/> </c:forTokens> This tag outputs a, b, c, d, and e, but not f, because the index of e in this collection is 4.

Looping over numbers


<c:forEach begin="1" end="5" var="current"> <c:out value="${current}"/> </c:forEach> Output: 1 2 3 4 5

<c:forEach begin="2" end="10" step="2" var="current"> <c:out value="${current}"/> </c:forEach>


Output: 2 4 6 8 10

Accessing Database with JSTL

<sql:setDataSource driver="org.hsqldb.jdbcDriver url="jdbc:hsqldb:. user="sa password="donkey scope="session" /> The <sql:setDataSource> tag does not support connection pooling. <sql:query var="result" sql="SELECT * FROM CUSTOMERS"/> <sql:query var="smartUsers"> SELECT NAME, IQ FROM USERS WHERE IQ > 120 </sql:query> <table> <c:forEach items="${smartUsers.rows}" var="row"> <tr> <td><c:out value="${row.NAME}"/></td> <td><c:out value="${row.IQ}"/></td> </tr> </c:forEach> </table>

Updating Database with JSTL

<sql:update> INSERT INTO PEOPLE(NAME, AGE, WEIGHT) VALUES(John "Fatso" Smith, 34, 540) </sql:update> <sql:update var="n"> DELETE FROM CUSTOMERS WHERE AGE < 18 </sql:update> <p>Our CUSTOMERS table had <c:out value="${n}"/> minors. They have all been removed. Close call; were lucky the Feds didnt come after us.</p>

<sql:query> SELECT * FROM USERS WHERE BIRTHDAY < ? <sql:dateParam value="${myBirthday}"/> </sql:query>

JSTL in Action
With this, you have covered approx. 8 chapters of the book JSTL in Action (Manning) For additional insight please refer the book Read Chapter 10 of the book regarding formatting & internationalization its interesting

Potrebbero piacerti anche