Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 41

JSTL

JSP is designed for the presentation layer in the web applications but it needs to contain the logic or code inside the page to control the way it presents the visual elements. Since JSP was born, scriptlet has been used intensively therefore the JSP pages become messy and difficult to maintain. The HTML mixed with JSP scriptlet and opening and closing brace make JSP page even hard to extend. JSP Standard tag library or JSTL provides JSP authors a better way to make the JSP page cleaner and more friendly.(i.e. simplify JSP development).

JSTL
JSTL provide two things 1.Robust set of tag libraries Encapsulates common functionality found in many web applications. Simplified HTML oriented syntax. 2. Expression language Used with JSTL to access Java Beans Introduced with JSP2.0 The goals of those tag library above are: Simplify the task of writing JSP page by providing friendly XML base tags Provide reusable logic from page's presentation Make the JSP page easier to read and maintain

JSTL
JSP Standard Tag Library (JSTL) was introduced to ease the programming in JSP by storing generic tasks in tag libraries. Syntax: <%@ taglib uri="URIToTagLibrary" prefix="tagPrefix" %> In the above example the "uri" points to the tag library . JSP standard tags library can be divided into five tag libraries which are: Core tags Internationalization (i18n) and formatting tags Relational database access tags XML processing tags Functions tags

JSP standard tags library


Library Core XML Processing l18N formatting Database access Functions URI http://java.sun.com/jsp/jstl/core http://java.sun.com/jsp/jstl/xml http://java.sun.com/jsp/jstl/fmt http://java.sun.com/jsp/jstl/sql Prefix c x fmt sql

http://java.sun.com/jsp/jstl/func Fn tion

Prerequisites for using JSTL


Jar file required for JSTL to be in the classpath of the application server jstl.jar : contains the classes for the tags. standard.jar: contains all the tld files Any JSP file should include the following directive to avail respective JSTL tags
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> for Core JSTL tags
<%@taglib uri="http://java.sun.com/jsp/jstl/xml" prefix=x"%> for XML JSTL tags <%@taglib uri="http://java.sun.com/jsp/jstl/sql" prefix=sql"%> for XML Tags <%@taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix=fmt%> for Formatting tags

Core Tag library

Core tags As its name imply, core tags provide the core functionality actions to JSP to make the most common actions easier to achieve in a more effective way. Core tags specify several actions such as displaying content based on condition, manipulating collections and URL managing. By using the core tags you'll never have to write scriptlet. But you still need to know scriptlet to maintain legacy web applications and convert them to JSTL later on if you have to.

Core Library
General-purpose
<c:out> <c:set> <c:remove> <c:catch>
Iteration <c:forEach> <c:forEachToken> URL related <c:import> <c:url> <c:redirect> <c:param>

Conditional
<c:if> <c:choose>
<c:when> <c:otherwise>

Servlet file - jsp file - useBean - jstl If we want to assign the value 'sam' to a variable 'a' and then print it, the JSTL code will be <c:set var="a" value="sam" /> <c:out value="${a}" />

jstl1.jsp
<body> <c:set var="a" value="sam" /> <c:out value="${a}" /> <%--<form action="jstl2.jsp" method="post"> FirstName:<input type="text" name="fname" /><br /> LastName:<input type="text" name="lname" /><br /> <input type="submit" value="submit" /> </form> --%> </body>

jstl2.jsp
<body> First Name: <c:out value="${param.fname}"></c:out> <br /> Last Name: <c:out value="${param.lname}"></c:out> </body>

Example of JSP without JSTL tags

Jstl3.jsp<%@page contentType="text/html" pageEncoding="UTF-8"%>


<html> <head> <title>JSP scriptlet</title> </head> <body> <table border="1" width="100px"> <% for (int c = 1; c < 10; c++) { if (c % 2 == 0) { %> <tr> <td><%=c%></td> </tr> <% } else { %> <tr> <td><%=c%></td> </tr> <% } } %> </table> </body> </html>

Same Example with JSTL

Jstl4.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <html> <head> <title>JSTL page</title> </head> <body> <table border="1" width="100px"> <c:forEach begin="1" end="10" step="1" var="c"> <c:choose> <tr> <c:when test="${c%2 ==0}"> <td><c:out value="${c}" />

</td>
</tr> </c:when> <c:otherwise> <tr> <td><c:out value="${c}" /> </td> </tr> </c:otherwise> </c:choose> </c:forEach> </table> </body> </html>

CoreTags --- <c:cout>


<c:out> action is used to evaluate a variable or expression and output it. <c:out> is similar to the expression <%= expression%>. The usage of <c:out> action is as follows: <c:out value="variable" default="default value"/> <c:out value="expression" default="default value" /> There are two attributes: Value: You can put a variable or expression here default value: if the variable or expression is evaluated as null, the default value will be used for output.

<c:out> Example
jstl5.jsp <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <html> <head> <title>c:out Example</title> </head> <body> <c:out value=this tag is easy" /><br> <c:out value="${header.Host}"> </c:out> ABC </body> </html>

<c:set > to allow you to init or set a variable of the web application in a specific scope. The usage of the c:set is as follows: <c:set var = "variable value = "value scope = "scope" /> In the var attribute you can declare or refer to a variable. The value attribute specify the value of the variable. If you want to set the scope of the variable, you can use the scopeattribute. The scope attribute accepts any valid JSP variable scopes such as page,request, session and application. Let's take a look at an example of using c:set action.

<c:set> Example
jstl6.jsp <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <html> <head><title>c:set Example</title></head> <body> <% request.setAttribute("name","Jasmine");%> <c:set var="name" value="Rose" scope="request"/> ${name} <br> <c:set var="name" scope="request"> ${header.host} ${requestScope.name} </c:set> ${name} <br> </body> </html>

<c:remove>
Removes a variable from the specified scope. Syntax: <c:remove var=varname [scope={page|request|session|appl ication}]>

<c:catch>
Catches exception thrown by any tag in its body. Syntax <c:catch [var=varname]> nested actions </c:catch>

Example
jstl7.jsp <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <html><head> <title>c:remve and c:catch Example</title></head> <body> <c:catch var="x"> <jsp:useBean id="cust" class="app1.CustomerBean" scope="session"> <jsp:setProperty name="cust" property="name" value="Kartik"/> </jsp:useBean> <c:remove var="cust" scope="session"/> <jsp:setProperty name="cust" property="name" value="Dolly"/> </c:catch> <br>Exception : ${x} </body></html>

public class CustomerBean { String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }

<c:if>
If the value of attribute is true the body is executed. Syntax With body <c:if test=testCondition var=varName scope={page|request|session| application}/> Without body <c:if test=testCondition [var=varName] [scope={page|request|session|application}]> body content </c:if>

Example
8.jsp <%@page isELIgnored="false"%> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <html> <head> <title>Check The Name</title> </head> <body> <center> <b>Welcome to our page!</b> </center> <c:if test="${empty param.tname}" var="test" > <jsp:forward page="error.jsp" /> </c:if> Hello ${param.tname} <br> Test Result : ${test} </body> </html>

<c:choose>
Like the switch statement Syntax <c:choose> body content (<c:when> and <c:otherwise>) <c:when test=testcondition> body content </c:when> <c:otherwise> body content </c:otherwise>

Example
9.jsp <c:choose> <c:when test="${param.rad == 'JAVA'}" > java.lang.Thread class or java.lang.Runnable interface </c:when> <c:when test="${param.rad == 'JVM'}" > Java Virtual Machine </c:when> <c:when test="${param.rad == 'Servlet'}" > javax.http.servlet package </c:when> <c:when test="${param.rad == 'JSP'}" > Java Server Pages. </c:when> <c:otherwise>Noting selected </c:otherwise> </c:choose>

Jstlchoose0.jsp Jstlchoose.jsp

<c:forEach>
Used to iterate over a collection. Syntax Iterate over a collection <c:forEach items=collection [var=varname] [varStatus=varStatusName] [begin=begin] [end=end] [step=step]> body content </c:forEach>

Iterate a fixed number of times <c:forEach [var=varname] [varStatus=varStatusName] begin=begin end=end [step=step]> body content </c:forEach>

Example
10.jsp <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <html><head><title>Book List</title> </head> <body> <c:forEach var="i" begin="10" end="20" step="2"> ${i}<br> </c:forEach> <center><b>You have selected the following books.</b><hr><br> <table> <c:forEach var="book" items="${paramValues.bookname}" > <tr> <td> ${book}</td> </tr> </c:forEach> </table> </body> </html>

<c:forTokens>
Used to loop over tokenized elements of a string like StringTokenizer. Syntax <c:forTokens items=stringOfTokens delims=delimiters [var=varName] [varStatus=varStatusName] [begin=begin] [end=end] [step=step]> Body content </c:forTokens> Example <c:forTokens items="$104200$4000$9000" delims="$" var="i"> ${i}<br> </c:forTokens>

<c:import>
Used like <jsp:include> but with the exception to include pages even out of the same servlet context. Syntax The resource to be included in the specified variable name <c:import url=url [context=context] [var=varName] [scope={page|request|session| application}] [charEncoding=charEncoding]> optional body content </c:import>

11.jsp <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <html> <head> <title>c:import Example</title> </head> <body> <h1>ABC.com</h1> <hr /> <c:import var="data" url="http://www.javafasttrack.com"> </c:import> <h2>Data is:</h2> <c:out value="${data}"></c:out> </body> </html>

<c:redirect>
Used to send HTTP redirect. Similar to HttpServletResponse.sendRedirect Syntax Without body content <c:redirect url=value [context=context]/> With query string parameters <c:redirect url=value [context=context]> <c:param> subtags </c:redirect> Example: <c:redirect url='${param.page}'/>

fn.length() Returns the number of items in a collection, or the number of characters in a string.
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %> <html> <head> <title>JSTL Functions</title> </head> <form> USERNAME:<input type="text" name="usr" size="25"> <p></p> <input type="submit" value="Submit"> <input type="reset" value="Reset"> </form> <br> Length of your Username is:: <c:out value="${fn:length(param.usr)}" />

Internationalization(I18L) and formatting tags


Those tags specify a series actions to make the web application multilingual. Those actions including managing resource bundle, locales and base names.

Internationalization(I18L) and formatting tags


Setting Locale
<fmt:setLocale> <fmt:requestEncoding>
Numbering and Date formating <fmt:formatNumber> <fmt:formatDate> <fmt:parseDate> <fmt:parseNumber> <fmt:setTimeZone> <fmt:timeZone>

Messaging
<fmt:bundle> <fmt:message>
<fmt:param> <fmt:setBundle>

Relational database access tags


Accessing database is a most major task of web applications. JSTL provides a list of standard tags to help you to manipulate data such as select, insert, update and delete from the relational databases.

Relational database access tags


SQL
<sql:setDataSource> <sql:query>
<sql:param> <sql:dateParam>

<sql:transaction> <sql:update>
<sql:param> <sql:dateParam>

XML processing tags


XML becomes a standard of enterprise web application for exchanging data. Manipulate XML effectively therefore is very important for most web applications and of course JSTL also provides a list of tags for processing from XML parsing to XML transformation.

XML Library
General-purpose
<x:out> <x:set> <x:parse>
Iteration <xml:forEach> Transform <x:transform> <x:param>

Conditional
<c:if> <x:choose>
<xml:when> <xml:otherwise>

Function Library
Collection length
<fn:length>
<fn:endsWith> <fn:split> <fn:join> <fn:contains>

String Manupilation
<fn:toUpperCase> <fn:toLowerCase> <fn:substringBefore> <fn:trim> <fn:replace> <fn:startWith>

You might also like