Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0...

80
Middleware Technology JavaServer Pages (JSP)

Transcript of Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0...

Page 1: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

Middleware TechnologyJavaServer Pages (JSP)

Page 2: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

2

Agenda

• Developing JSP-based Web Application

• JSP 2.0 (in J2EE 1.4)– EL– JSTL– Custom tags in JSP pages

Page 3: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

3

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)

Page 4: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

4

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-rea

dy directory) • 5.Deploy the web application into a Web container

– Web clients are now ready to access them via URL

Page 5: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

5

Example

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

Page 6: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

6

Example.

Page 7: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

7

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

Page 8: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

8

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

Page 9: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

9

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.

Page 10: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

10

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 JS

P files, such as page encoding or automatic includes before and after pages, etc

Page 11: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

11

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>

Page 12: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

12

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>

<servlet-name>greeting</servlet-name><url-pattern>/greeting</url-pattern>

</servlet-mapping></web-app>

Page 13: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

13

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

Page 14: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

14

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 bu

ild.xml file– Use “jar cvf <filename>.war .” command under build

directory

Page 15: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

15

Directory Structure of *.WAR file

Page 16: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

16

Install or Deploy Web application

• There are 2 different ways to install/deploy Web application– By manually copying files to Tomcat's webapps directo

ry 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

Page 17: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

17

Perform Client Access to Web Application

• From a browser, go to URL of the Web application

• http://localhost:8080/hello/greeting

Page 18: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

18

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

Page 19: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

JSP 2.0 (in J2EE 1.4)

Page 20: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

20

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.

Page 21: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

21

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>

Page 22: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

22

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.

Page 23: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

23

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"]}

Page 24: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

24

Example 1

• Using scriptlets:

• Equivalent, using an EL expression:

<center>

<jsp:useBean id="foo" class="FooBean" />

<%= foo.getBar() %>

</center>

<center>

${foo.bar}

</center>

Page 25: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

25

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}

Page 26: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

26

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 -->

Page 27: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

27

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,",")}

Page 28: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

28

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

Page 29: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

29

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.

Page 30: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

30

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.

Page 31: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

31

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") : "" %>

Page 32: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

32

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 acce

ssed:

• servletContext

• session

• sequest/response

– For example, the context path can be accessed as:

• ${pageContext.request.contextPath}

Page 33: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

33

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}

Page 34: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

34

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 Ht

tpServletRequest.getCookies()– If there are multiple cookies with the same name, only the first o

ne encountered is placed in the map

Page 35: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

35

JSP EL: Implicit Objects 4

• Additional implicit objects are available for accessing scope attributes:– pageScope– requestScope– sessionScope– applicationScope

• For example:– ${sessionScope.user.userid}

Page 36: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

36

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 -- >

Page 37: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

37

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);  

 }

}

Page 38: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

38

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.

Page 39: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

39

JSP EL: Using EL Functions

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

Page 40: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

40

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.

Page 41: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

41

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>

Page 42: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

42

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

Page 43: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

43

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.

Page 44: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

44

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.

Page 45: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

45

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 />

<% }

}

%>

Page 46: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

46

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>

Page 47: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

47

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.

Page 48: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

48

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

Page 49: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

49

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" %>

Page 50: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

50

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

Page 51: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

51

JSTL: Core Tags

• General-purpose: – out set catch remove

• Flow control: – forEach forTokens

• Conditional:– if choose when otherwise

• URL management: – url import redirect param

Page 52: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

52

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>

Page 53: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

53

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/>

Page 54: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

54

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> <c:set var="name3" scope="session" >

value 3 in body </c:set> <c:set var="name4" scope="application">

value 4 in body </c:set>

Page 55: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

55

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>

Page 56: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

56

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" />

Page 57: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

57

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 p

age 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.

Page 58: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

58

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>

Page 59: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

59

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>

Page 60: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

60

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

Page 61: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

61

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>

Page 62: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

62

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>

Page 63: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

63

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>

Page 64: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

64

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>

Page 65: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

65

JSTL Tags: <c:url>

• This tag provides automatically encoded URLs.

• Session information and parameters are encoded with a URL.

• Example: urlDemo.jsp

Page 66: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

66

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

Page 67: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

67

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 attr

ibute

<c:when test="${param.action == ’buy’}"> <c:redirect context="/brokerage" url="/buy.jsp"> <c:param name="stock" value="IBM"/> </c:redirect></c:when>

Page 68: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

68

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" />

Page 69: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

69

<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>

Page 70: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

70

Other Tags

• Database tags:– <sql:setDataSource>,<sql:query>,<sql:update>…

• XML manipulation tags:– <x:parse>, <x:if>…

• Formatting tags:– <fmt:formatNumber>…

• Functions tags:– <fn:length>, <fn:indexof>…

Page 71: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

71

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

Page 72: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

72

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 J

SP 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

Page 73: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

73

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.

Page 74: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

74

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");

}

}

Page 75: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

75

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.

Page 76: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

76

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>

Page 77: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

77

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>

Page 78: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

78

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

Page 79: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

79

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>

Page 80: Middleware Technology JavaServer Pages (JSP). 2 Agenda Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) –EL –JSTL –Custom tags in JSP pages.

80

Learn More about JSTL

• JSTL in Action