Middleware Technology JavaServer Pages (JSP)

Slides:



Advertisements
Similar presentations
9 Copyright © 2005, Oracle. All rights reserved. Modularizing JavaServer Pages Development with Tags.
Advertisements

JSP and web applications
© Yaron Kanza Advanced Java Server Pages Written by Dr. Yaron Kanza, Edited by permission from author by Liron Blecher.
Expression Language Lec Umair Javed©2006 Generating Dynamic Contents Technologies available  Servlets  JSP  JavaBeans  Custom Tags  Expression.
CS320 Web and Internet Programming Java Beans and Expression Language (EL) Chengyu Sun California State University, Los Angeles.
Object-Oriented Enterprise Application Development Tomcat 3.2 Configuration Last Updated: 03/30/2001.
WEB1P servintro1 Introduction to servlets and JSP Dr Jim Briggs.
DT211/3 Internet Application Development
1 Build a Web Application on J2EE. 2 J2EE Scenario Client – Web Server – EIS Resources Client – Web Server – EIS Resources Client – Application Server.
Web programming for project students Dr Jim Briggs.
JSP Architecture  JSP is a simple text file consisting of HTML or XML content along with JSP elements  JSP packages define the interface for the compiled.
Creating a.war file W(eb) AR(chive). Creating a.war file The following article may contain actual software programs in source code form. This source code.
Web Applications Basics. Introduction to Web Web features Clent/Server HTTP HyperText Markup Language URL addresses Web server - a computer program that.
Introduction to Java web programming Dr Jim Briggs JWP intro1.
Java Enterprise Edition Java Web Development Structure of a web project Introduction to Web Applications The first project Introduction to Java Web Development.
Overview of JSP Technology. The need of JSP With servlets, it is easy to – Read form data – Read HTTP request headers – Set HTTP status codes and response.
1 CIS336 Website design, implementation and management (also Semester 2 of CIS219, CIS221 and IT226) Lecture 9 JavaServer Pages (JSP) (Based on Møller.
Java Server Pages CS-422. What are JSPs A logical evolution of java servlets –most servlets dynamically create HTML and integrate it with some computational.
M. Taimoor Khan * Java Server Pages (JSP) is a server-side programming technology that enables the creation of dynamic,
JSP Standard Tag Library
Using JavaBeans and Custom Tags in JSP Lesson 3B / Slide 1 of 37 J2EE Web Components Pre-assessment Questions 1.The _____________ attribute of a JSP page.
AN OVERVIEW OF SERVLET TECHNOLOGY SERVER SETUP AND CONFIGURATION WEB APPLICATION STRUCTURE BASIC SERVLET EXAMPLE Java Servlets - Compiled By Nitin Pai.
® IBM Software Group © 2007 IBM Corporation JSP Custom Tags
Introduction to Java Server Pages (JSPs) Robert Thornton.
Chapter 7 Java Server Pages. Objectives Explain how the separation of concerns principle applies to JSP Describe the operation and life-cycle of a JSP.
Introduction to JavaServer Pages (JSP) Slides from Dr. Mark Llewellyn.
Java Server Pages A JSP page is a text-based document that contains two types of text: static template data, which can be expressed in any text-based format,
JSP Most of the web developers deploying web applications using servlets mixes the presentation logic and business logic. Separation of business logic.
® IBM Software Group © 2007 IBM Corporation JSP Expression Language
JAVA SERVER PAGES. 2 SERVLETS The purpose of a servlet is to create a Web page in response to a client request Servlets are written in Java, with a little.
Lecturer: Prof. Piero Fraternali, Teaching Assistant: Alessandro Bozzon, Advanced Web Technologies: Struts–
Stanisław Osiński, 2002JSP – A technology for serving dynamic web content Java Server Pages™ A technology for serving dynamic web content Stanisław Osiński,
JAVA SERVER PAGES CREATING DYNAMIC WEB PAGES USING JAVA James Faeldon CS 119 Enterprise Systems Programming.
JSTL, XML and XSLT An introduction to JSP Standard Tag Library and XML/XSLT transformation for Web layout.
J2EE Overview Web Programming CSCI J2EE multi-tier architecture Servlet: Java class loaded into Web server JSP page: enhanced HTML page that is.
JSTL: The JavaServer Pages Standard Tag Library Mark A. Kolb Security Broadband, Austin, TX
JSTL Lec Umair©2006, All rights reserved JSTL (ni) Acronym of  JavaServer Pages Standard Tag Library JSTL (like JSP) is a specification, not an.
Fall 2007cs4201 Advanced Java Programming Umar Kalim Dept. of Communication Systems Engineering
Introduction to JavaServer Pages. 2 JSP and Servlet Limitations of servlet  It’s inaccessible to non-programmers JSP is a complement to servlet  focuses.
CS320 Web and Internet Programming Java Beans and Expression Language (EL) Chengyu Sun California State University, Los Angeles.
Writing Enterprise Applications with J2EE (Fourth lesson) Alessio Bechini June 2002 (based on material by Monica Pawlan)
JSP Tag Libraries Lec Last Lecture Example We incorporated JavaBeans in “Course Outline” Example But still have to write java code inside java.jsp.
Java server pages. A JSP file basically contains HTML, but with embedded JSP tags with snippets of Java code inside them. A JSP file basically contains.
COMP 321 Week 10. Overview Using Beans in JSP Expression Language JSTL Lab 10-1 Introduction Exam Review.
Copyright © 2002 ProsoftTraining. All rights reserved. JavaServer Pages.
A seminar on j2ee by saritha. s. What is J2EE J2EE (Java 2 Platform, Enterprise Edition) is a Java platform designed for the mainframe-scale computing.
CS320 Web and Internet Programming Custom Tag Library Chengyu Sun California State University, Los Angeles.
JSP Expression Language (EL) 25-Nov-15. JSP - E XPRESSION L ANGUAGE (EL) Introduction Expression Language was first introduced in JSTL 1.0 (JSP Standard.
JSP Custom Tags. Prerequisites Servlet API Mapping to JSP implicit objects JavaServer Pages Basic syntax Implementation via servlet API XML.
CSC 2720 Building Web Applications JavaServer Pages (JSP) JSP Directives and Action Elements.
JSP BASICS AND ARCHITECTURE. Goals of JSP Simplify Creation of dynamic pages. Separate Dynamic and Static content.
JAVA BEANS JSP - Standard Tag Library (JSTL) JAVA Enterprise Edition.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 JSP Application Models.
Basic JSP Celsina Bignoli Problems with Servlets Servlets contain –request processing, –business logic –response generation all lumped.
COMP9321 Web Application Engineering Semester 2, 2015 Dr. Amin Beheshti Service Oriented Computing Group, CSE, UNSW Australia Week 3 1COMP9321, 15s2, Week.
1 Java Server Pages A Java Server Page is a file consisting of HTML or XML markup into which special tags and code blocks are inserted When the page is.
Chapter 6 Chapter 6 Server Side Programming (JSP) Part 1 1 (IS 203) WebProgramming (IS 203) Web Programming.
Intermediate JSP Matt Wheeler. Notes This is a training NOT a presentation Please ask questions Prerequisites – Introduction to Java Stack – Basic Java.
JSP JavaServer Pages. What is JSP? Java based technology that simplifies the development of dynamic web sites JSP pages are HTML pages with embedded code.
Java Programming: Advanced Topics 1 Building Web Applications Chapter 13.
Topics to be covered (ni) Client side validation JSF (free tools as well) Webservices Tell Resources e.g. sites Packaging and deploying web applications.
CS320 Web and Internet Programming Custom Tag Library Chengyu Sun California State University, Los Angeles.
Lecture Transforming Data: Using Apache Xalan to apply XSLT transformations Marc Dumontier Blueprint Initiative Samuel Lunenfeld Research Institute.
JSP: Actions elements and JSTL
JSP (Java Server Page) JSP is server side technology which is used to create dynamic web pages just like Servlet technology. This is mainly used for implementing.
Developing JavaServer Pages
Knowledge Byte In this section, you will learn about:
CS320 Web and Internet Programming Expression Language (EL)
CS3220 Web and Internet Programming Expression Language (EL)
CS3220 Web and Internet Programming Expression Language (EL)
Presentation transcript:

Middleware Technology JavaServer Pages (JSP)

Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) EL JSTL Custom tags in JSP pages

Web Application & Components Web Application is a deployable package Web components (Servlets and JSP's) Static resource files such as images Helper classes Libraries Deployment descriptor (web.xml file) Web Application can be represented as A hierarchy of directories and files (unpacked form) or *.WAR file reflecting the same hierarchy (packed form)

Web Application Development and Deployment Steps 1.Write (and compile) the Web component code (Servlet or JSP) and helper classes referenced by the web component code 2.Create any static resources (for example, images or HTML pages) 3.Create deployment descriptor (web.xml) 4.Build the Web application (*.war file or deployment-ready directory) 5.Deploy the web application into a Web container Web clients are now ready to access them via URL

Example Tomcat将JSTL默认放在了jsp-examples目录中, greeting.jsp应该放在那里

Example.

Write and compile the Web component code Create development tree structure Write either servlet code or JSP pages along with related helper code IDE (i.e. NetBeans, Eclipse with Plugin) handles all these chores

Create any static resources HTML pages Custom pages Login pages Error pages Image files that are used by HTML pages or JSP pages Example: duke.waving.gif

Development Tree Structure JSP file can be placed under the deployment directory together with the main HTML files. JSP files can also be mapped to specific URLs in the web.xml file.

Deployment Descriptor (web.xml) Every web application has to have web.xml The configuration information for JSP pages is described in the web.xml file rooted on the <jsp-config> element. Configuration elements may include: <taglib> - element in mapping of tag libraries <jsp-property-group> - properties of collections of JSP files, such as page encoding or automatic includes before and after pages, etc

Example: Deployment Descriptor Common header and footer for JSP file can be defined in the web.xml file as follows: <?xml version="1.0" encoding="UTF-8"?> <web-app> <jsp-config> <jsp-property-group> <url-pattern>*.jsp</url-pattern> <include-prelude>/header.jsp</include-prelude> <include-coda>/footer.jsp</include-coda> </jsp-property-group> </jsp-config> </web-app>

Mapping JSP to a URL A JSP page can be mapped to a specific URL by modifying the web.xml file. <?xml version="1.0" encoding="UTF-8"?> <web-app> <servlet> <servlet-name>greeting</servlet-name> <jsp-file>/greeting.jsp</jsp-file> </servlet> <servlet-mapping> <url-pattern>/greeting</url-pattern> </servlet-mapping> </web-app>

Example: Mapping JSP Investigate the mapping mechanism for JSP file. Create a JSP Put it under the directory <your_web_context>/WEB-INF/classes/ Browse it with a web browser

Build the Web application Either *.WAR file or unpacked form of *.WAR file Build the “.war” file Use IDE (Eclipse with Lomboz) Use ant tool after putting proper build instruction in build.xml file Use “jar cvf <filename>.war .” command under build directory

Directory Structure of *.WAR file

Install or Deploy Web application There are 2 different ways to install/deploy Web application By manually copying files to Tomcat's webapps directory and then restarting Tomcat By asking Tomcat Manager via sending a command to it (Tomcat Manager is just another Servlet app that is always running) ant install ant deploy

Perform Client Access to Web Application From a browser, go to URL of the Web application http://localhost:8080/hello/greeting

Document Root & Context Document Root of the Web application Top-level directory of WAR Contains JSP pages, client-side classes and archives, and static Web resources are stored Also contains WEB-INF directory A context is a name that gets mapped to the document root of a Web application /hello is context for hello example Distinguishes a Web application in a single Web container Has to be specified as part of client URL

JSP 2.0 (in J2EE 1.4)

JSP 2.0 Expression Language JSP-specific expression language(JSP EL), is defined in JSP 2.0 specification. JSP EL provides a cleaner syntax and is designed specially for JSP.

JSP EL Examples A variable can be accessed as: ${variable_name} The property can be accessed as: <c:if test="${aBean.age < 20}"> … </c:if>

JSP EL: Syntax In JSP EL, expressions are always enclosed by ${} characters. Any values not begin with ${ is literal. Literal value containers the ${ has to be escaped with “\” character.

JSP EL: Attributes Attributes are accessed by name, with an optional scope. Members, getter methods, and array items are all accessed with a “.” Examples: A member b in object a ${a.b} A member in an array a[b] ${a.b} or ${a["b"]}

Example 1 Using scriptlets: Equivalent, using an EL expression: <center> <jsp:useBean id="foo" class="FooBean" /> <%= foo.getBar() %> </center> <center> ${foo.bar} </center>

Example 2 Using scriptlets: Equivalent, using an EL expression: <% Map m = (Map)pageContext.getAttribute("state" ); State s = ((State)m.get( "NY" )); if( s != null ) { %> <%= s.getCapitol() %> <% } %> ${state["NY"].capitol}

Data structures: arrays, maps, sets Arrays and maps permit access to their collection via indices arrays via integer indices maps via key indices. EL regards both of these accesses as syntactically similar using the [ ] operator. <% Map<String,String> theMap = new HashMap<String,String>(); theMap.put("John", "5"); theMap.put("Jim", "7"); String theArray[] = { "aaa", "bbb", "ccc" }; session.setAttribute( "theMap", theMap ); session.setAttribute( "theArray", theArray ); %> ${theMap["Jim"]} <!-- same as theMap.get("Jim"), outputs 7 --> ${theArray[1]} <!-- outputs bbb -->

Data structures: arrays, maps, sets The EL expressions for maps, sets and lists can all print directly. Arrays, as in Java, don't print directly, but must use an auxiliary function. In this case the fn:join function serves the purpose: ${fn:join(theArray,",")}

JSP EL: Operators [] . () - Used to change the precedence of operators. - (unary) not ! empty * / div % mod + - (binary) < > <= >= lt gt le ge == != eq ne && and || or ? : Note: order of preference from top to bottom, left to right

Notes for EL The == operator for strings functions like the Java .equals operator. An EL expression with an undefined value, which (normally represented by null in Java) is also represented by null in EL, but is equivalent to the empty string. EL has a unary operator empty: empty(x) acts like the expression x==null but also means "x equals the empty string". The operators or, and are synonyms for ||, &&, respectively.

Reserved Words The following words are reserved for the JSP expression language and should not be used as identifiers. and   eq   gt   true   instanceof or    ne   le   false  empty not   lt   ge   null   div   mod Note that many of these words are not in the language now, but they may be in the future, so you should avoid using them.

Query parameters The value of the parameter “xx” is expressed by the EL expression param.xx. (param是一个内置对象) Using an EL expression Equivalent, using scriptlets: ${param.xx} <%= (request.getParameter("xx") != null) ? (request.getParameter("xx") : "" %>

JSP EL: Implicit Objects 1 A set of implicit objects is defined to match the JSP equivalents: 1) pageContext: the context for the JSP page Through pageContext, the following implict objects can be accessed: servletContext session sequest/response For example, the context path can be accessed as: ${pageContext.request.contextPath}

JSP EL: Implicit Objects 2 2) param Maps name of parameter to a single string value Same as ServletRequest.getParameter(String name) E.g. ${param.name} 3) paramValues Map name of parameter to an array of string objects Same as ServletRequest.getParameterValues(String name) E.g. ${paramValues.name}

JSP EL: Implicit Objects 3 4) header Maps a request header name to a single string header value Same as HttpServletRequest.getHeader(String name) E.g. ${header.name} 5) headerValues Map request header names to an array of string objects Same as HttpServletRequest.getHeaders(String name) E.g. ${headerValues.name} 6) cookie Maps the single cookie objects that are available by invoking HttpServletRequest.getCookies() If there are multiple cookies with the same name, only the first one encountered is placed in the map

JSP EL: Implicit Objects 4 Additional implicit objects are available for accessing scope attributes: pageScope requestScope sessionScope applicationScope For example: ${sessionScope.user.userid}

Session variables are EL variables A session variable x automatically becomes available as an EL variable Example: <% session.setAttribute( "x", "hello" ); // or pageContext.setAttribute( "x", "hello" ); %> x = ${x} <!-- prints: x = hello -- >

JSP EL: Defining EL Functions 1 To define a function you program it as a public static method in a public class. package mypkg; public class MyLocales {    ...    public static boolean equals( String l1, String l2 ) {      return l1.equals(l2);    } }

JSP EL: Defining EL Functions 2 Map the function name as used in the EL expression to the defining class and function signature in a TLD (Tag Library Descriptor). <?xml version="1.0" encoding="UTF-8"?> <web-app>No two functions within a tag library can have the same name. <jsp-config> <taglib> <function>    <name>equals</name> <function-class>mypkg.MyLocales</function-class>   <function-signature> boolean equals( java.lang.String,  java.lang.String ) </function-signature> </function> </taglib> </jsp-config> </web-app> No two functions within a tag library can have the same name.

JSP EL: Using EL Functions The previous EL functions can be used as following: ${equals('string1', 'string2')}

JSP EL Compatibility Using JSP EL may cause compatibility problems with JSP1.2 and earlier code. JSP EL is disabled by default for a web application with a deployment descriptor that is not Servlet 2.4 conformant and it's enabled by default for a web application with a Servlet 2.4 deployment descriptor. JSP EL is enabled by default for a web applications with Servlet 2.4 deployment descriptor.

Enabling / Disabling JSP EL For a single page with the el-Ignored page attribute <%@ page isELIgnored="true|false"%> For a set of JSP pages with an <el-ignored> element in a JSP group: <web-app ...> ... <jsp-config> <jsp-property-group> <url-pattern>*.jsp</url-pattern> <el-ignored>true</el-ignored> </jsp-property-group> </jsp-config> ... </web-app>

Standard Tag Library JavaServer Pages Standard Tag Library (JSTL) is an extended set of JSP standard action includes the following tags: Iteration and conditional Expression language Url manipulation Internationalization-capable text formatting Xml manipulation Database access

Problems with JSP Scriptlet Tags Java code is embedded within scriptlet tags Non-Java developer cannot understand the embedded java code Java code within JSP scriptlets cannot be reused by other JSP pages Casting to the object’s class is required when retrieving objects out of HTTP request and session.

Advantage of JSTL JSTL tags are in xml format and can be cleanly and uniformly blended into a page’s html mark up tags. JSTL tag libraries are organized into four libraries which include most functionality required for a JSP page and are easier for non-programmers to use JSTL tags encapsulate reusable logic and allow to be reused. No casting is requiring while using JSTL referencing objects in the request and session JSP’s EL allows using dot notation to access the attributes of java objects.

Example: JSTL 1 Without JSTL, some scriplets may look as follows <% List addresses = (List)request.getAttribute("addresses"); Iterator addressIter = addresses.iterator(); while(addressIter.hasNext()) { AddressVo address = (AddressVo)addressIter.next(); if(address != null) {%> <%=address.getLastName() %><br /> <% } else { %> N/A<br /> <% } } %>

Example: JSTL 2 With JSTL, the previous may looks as follows <% taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <c:forEach item=${addresses} var="address" > <c:choose> <c:when test="${address != null}"> <c:out value="${address.lastName}"/><br/> <c:otherwise> N/A<br/> </c:otherwise> </c:choose> </c:forEach>

Using JSTL JSTL is standardized, but not a standard part of JSP 1.2 or 2.0 JSTL must be downloaded and installed separately before being used.

Installing the JSTL The JSTL will be installed and setup for used. Download the library from this URL: http://www.apache.org/dist/jakarta/taglibs/standard/ Unpack the file and two jar files are inside the /lib dirctory: jstl.jar standard.jar

<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> Installing the JSTL Copy the jar file to the following directory <Tomcat_Home>/common/lib The jar file can also be copied to the /WEB-INF/lib directory under your application context. In the JSP page, the following tags can be used to refer to the installed JSTL: <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

Organization of JSTL The JSTL tags are organized into five libraries Library features URI Prefix Core(control flow, URLs, variable access) http://java.sun.com/jsp/jstl/core c Text formatting http://java.sun.com/jsp/jstl/fmt fmt XML manipulation http://java.sun.com/jsp/jstl/xml x Functions http://java.sun.com/jsp/jstl/functions fn Database access http://java.sun.com/jsp/jstl/sql sql

JSTL: Core Tags General-purpose: Flow control: Conditional: out set catch remove Flow control: forEach forTokens Conditional: if choose when otherwise URL management: url import redirect param

JSTL Tags: <c:out> <%@page contentType="text/html;charset=gbk" %> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <html> <head><title>JSTL Example</title></head><body> 利用JSTL 打印1到10 <p> <c:forEach var="i" begin="1" end="10" step="1"> <c:out value="${i}" /> <br/> </c:forEach> <p>利用JSP的scriptlet 打印1到10 <p> <% for(int i=1;i<=10;i++) {%> <%=i%><br/> <% } %> </body></html>

JSTL Tags: <c:set> <%-- Declare the core library --%> <%@ taglib uri="/WEB-INF/tld/c.tld" prefix="c" %> <%-- Save data in scoped variables --%> <c:set var="name1" value="value1" scope="page" /> <c:set var="name2" value="value2" scope="request" /> <c:set var="name3" value="value3" scope="session" /> <c:set var="name4" value="value4" scope="application" /> <%-- Show the saved values --%> <c:out value='${pageScope.name1}' /><br/> <c:out value='${requestScope. name2}' /><br/> <c:out value='${sessionScope. name3}' /><br/> <c:out value='${applicationScope.}' /><br/>

JSTL Tags: <c:set> <%-- Save data using body content --%> <c:set var="name1" scope="page"> value 1 in body </c:set> <c:set var="name2" scope="request" > value 2 in body <c:set var="name3" scope="session" > value 3 in body <c:set var="name4" scope="application"> value 4 in body

JSTL Tags: <c:set> Set JavaBean property: <c:set target= "student_A" value= "pass" property= "grade"/> <c:set target= "target" value= "value" property= "propertyName"/> Body part </c:set>

JSP beans in JSTL The EL language provides a simplified syntax for accessing bean's get/set accessor functions. package bean; public class MyBean { private String count; public String getCount() { return count; } public void setCount(String count) { this.count = count; } public MyBean() { System.out.println("MyBean intialized"); count = "0"; } <jsp:useBean id="mb" class="bean.MyBean" /> <c:remove var="mb" />

JSTL Tags: <c:catch> This tag provides a complement to the JSP error page mechanism. It works as a try-catch statement. Code surrounded by catch tag will never cause the error page mechanism to be invoked. If a var attribute is set, the exception will be stored in the variable identified by the var attribute. The var attribute always has page scope.

JSTL Tags: <c:catch> <%@ taglib uri="/WEB-INF/tld/c.tld" prefix="c" %> <html> <head><title>The c:catch action</title></head>   <body>     <c:catch var="signalException">       <%         int i= (int) (Math.random() * 10); if (i < 5 )            throw new NullPointerException(); %>     </c:catch>    <c:choose>       <c:when test="${signalException != null}">          Exception occurs.       </c:when>       <c:otherwise>          No Exception.       </c:otherwise>     </c:choose>   </body></html>

JSTL Tags: <c:remove> <%@ taglib uri="/WEB-INF/tld/c.tld" prefix="c" %> <c:set var="userName" value="Mark" scope="session" /> <html><head><title>Set a scoped attribute</title></head>   <body>     This page sets a session-scoped attribute that is removed     by <a href="removeAttribute.jsp">this</a> page.   </body> </html> <%@ taglib uri="/WEB-INF/tld/c.tld" prefix="c" %> <html><head><title>Remove a scoped attribute</title></head> <body>  The session-coped attribute called <b>userName</b> had a value  of <b> <c:out value="${sessionScope.userName}" /> </b>, but it is about to be removed!<p/> <c:remove var="userName" scope="session" />    The value is now "<c:out value="${sessionScope.userName}" />"   </body></html> Remove a scope variable

JSTL Tags: <c:forEach> This tag provides iteration over a collection of objects. Supports iteration over an array java.util.Collection java.util.Iterator java.util.Enumeration Java.util.Map

JSTL Tags: <c:forEach> This tag provides iteration over a collection of objects. See foreach.jsp <c:set var="str" value="Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday" />     <c:out value="${str}" /> <c:forEach var="day" items="${str}"> <c:out value="${day}" /> <br /> </c:forEach>

JSTL Tags: <c:forTokens> The forTokens tag is used to iterate over a collection of tokens separated by a delimiter See foreach.jsp <form method="post"> Enter a sentence: <input width="20" name="text" size="50" /> <input type="submit" name="parse" value="Parse" /> </form> <c:if test="${pageContext.request.method=='POST'}"> <c:forTokens items="${param.text}" var="word" delims=" ,.?!"> <c:out value="${word}" /> </c:forTokens> </c:if>

JSTL Tags: <c:if> This tag works similar to a Java if and switch See ifDemo.jsp <c:if test="${ user == null}" > <form> Name: <input name = "name" > Password: <input name = "pass "> </form> </c:if>

JSTL Tags: <c:choose> For more than one options, use <c:choose>,<c:when> and <otherwise> tag, see chooseDemo.jsp <c:choose> <c:when test="${user == null}"> <form> Name: <input name = "name" > Password: <input name = "pass“> </form> </c:when> <c:otherwise> welcome ${user.name} </c:otherwise> </c:choose>

JSTL Tags: <c:url> This tag provides automatically encoded URLs. Session information and parameters are encoded with a URL. Example: urlDemo.jsp

Attributes of <c:url> tag value: provides the URL to be processed context: defines the name of the context var: exports the encoded URL to a scoped variable scope:defines the scope of the var object <c:url var="thisURL" value="newPage.jsp"> <c:param name="aVariable" value="${v.id}"/> <c:parm name="aString" value="Simple String" /> <c:/url> <a href="<c:out value="${thisURL}"/>">Next</a> The above generates a URL as following: newPage.jsp?aVariable=2&aString=Simple+String

JSTL Tags:<c:redirect> This tag provides the functionality to call the HttpServletResponse.sendRedirect method. It can have attributes as follows: url: the URL should be redirected to context: the context of the URL specified by the url attribute <c:when test="${param.action == ’buy’}"> <c:redirect context="/brokerage" url="/buy.jsp"> <c:param name="stock" value="IBM"/> </c:redirect> </c:when>

JSTL Tags: <c:import> Include text in a JSP page <jsp:include> <%@ include%> <c:import> This tag provides all of the functionality of the include Action. It allows for inclusion of absolute URLs, e.g. the content from a different web site. Example: <%@ taglib uri="/WEB-INF/tld/c.tld" prefix="c" %> <c:import url="http://www.yahoo.com" />

<c:import> Example <c:catch var="exception"> <c:import url="ftp://ftp.example.com/package/README"/> </c:catch> <c:if test="${not empty exception}"> Sorry, the remote content is not currently available. </c:if>

Other Tags Database tags: XML manipulation tags: Formatting tags: <sql:setDataSource>,<sql:query>,<sql:update>… XML manipulation tags: <x:parse>, <x:if>… Formatting tags: <fmt:formatNumber>… Functions tags: <fn:length>, <fn:indexof>…

Custom tags in JSP pages A custom tag is a user-defined JSP language element. JSP custom tag is based on javax.servlet.jsp.tagext SimpleTag interface

SimpleTag Interface All SimpleTag classes should implement the javax.servlet.jsp.tagext.SimpleTag Interface The interface defines the following methods: doTag() -Implemented by the tag developer and invoked by a JSP container during execution getParent() -Returns the custom tag surrounding this tag setJspBody(javax.servlets.jsp.JspFragment) – invoked by a JSP container during runtime before thedoTag() method setJspContext(javax.servlets.jsp.JspContext) – invoked by a JSP container during runtime before the doTag() method setParent(javax.servlets.jsp.JspTag) – invoked by a JSP container during runtime to set the current parent tag

How to develop simple tags The javax.servlet.jsp.tagext.SimpleTagSupport class is the base implementation of the SimpleTag interface. A custom tag can extend SimpleTagSupport and override the doTag() method.

Develop a simple tag package com.web; import javax.servlet.jsp.tagext.SimpleTagSupport; import javax.servlet.jsp.*; import java.io.IOException; public class HelloSimpleTag extends SimpleTagSupport { public void doTag() throws JspException, IOException { JspWriter out = getJspContext().getOut(); out.println("Hello World"); } Create a class named HelloSimpleTag. This class should be a subclass of SimpleTagSupport class Allow the tag output a string in the doTag() method.

How to Use Custom Tags A collection of custom tags designed for a common goal can be packaged into a library. The custom tags within the library can be used by a JSP as described by a Tag Library descriptor (TLD) file.

Tag Library Descriptor Tag Library Descriptor is an XML file with .tld extension <?xml version="1.0" encoding="UTF-8" ?> <taglib xmlns=http://java.sun.com/xml/ns/j2ee xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance xsi:schemaLocation=http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd version="2.0"> <tlib-version>1.1</tlib-version> <short-name>ex</short-name> <tag> <name>hello</name> <tag-class>com.web.HelloSimpleTag</tag-class> <body-content>empty</body-content> </tag> </taglib>

TLD: Tag Elements All tag definitions must be nested inside the <taglib> element The following tags are mandatory and should appear only once: <tlib-version>1.0</tlib-version> <short-name>ex</short-name>

TLD: Tag Elements Each tag is defined by a <tag> element. Within the <tag> element, the following attribute tags could be defined: <name>: unique element name of the custom tag <tag-class>:full class name for the tag class <body-content>:type of code allowed to be inserted into the body of the customer tag when used by a JSP: empty - tag body should be empty JSP - tag body maybe empty or containing scripting elements scriptless – no scripting elements allowed tagdependent – the body may contain non-JSP content like SQL statements

Using Tag Library Define a relative URI in JSP file <%@ taglib uri="/WEB-INF/tld/example.tld" prefix="ex" %> <html> <head> <title>text custom tag</title> </head> <body> <ex:hello/> </body> </html>

Learn More about JSTL JSTL in Action