Transcript c:when

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
2
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)
3
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 deploymentready directory)
• 5.Deploy the web application into a Web container
– Web clients are now ready to access them via URL
4
Example
Tomcat将JSTL默认放在了jsp-examples目录中, greeting.jsp应该放在那里
5
Example.
6
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
7
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
8
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.
9
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 <jspconfig> 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
10
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>
11
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>
12
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
13
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
14
Directory Structure of *.WAR file
15
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
16
Perform Client Access to Web Application
• From a browser, go to URL of the Web application
• http://localhost:8080/hello/greeting
17
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
18
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.
20
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>
21
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.
22
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 member in an array a[b]
${a.b}
${a.b} or ${a["b"]}
23
Example 1
• Using scriptlets:
<center>
<jsp:useBean id="foo" class="FooBean" />
<%= foo.getBar() %>
</center>
• Equivalent, using an EL expression:
<center>
${foo.bar}
</center>
24
Example 2
• Using scriptlets:
<% Map m = (Map)pageContext.getAttribute("state" );
State s = ((State)m.get( "NY" ));
if( s != null ) {
%>
<%= s.getCapitol() %>
<% } %>
• Equivalent, using an EL expression:
${state["NY"].capitol}
25
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 -->
26
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,",")}
27
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
28
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.
29
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.
30
Query parameters
• The value of the parameter “xx” is expressed by
the EL expression param.xx. (param是一个内置对象)
• Using an EL expression
${param.xx}
• Equivalent, using scriptlets:
<%= (request.getParameter("xx") != null) ?
(request.getParameter("xx") : "" %>
31
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}
32
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}
33
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
34
JSP EL: Implicit Objects 4
• Additional implicit objects are available for
accessing scope attributes:
–
–
–
–
pageScope
requestScope
sessionScope
applicationScope
• For example:
– ${sessionScope.user.userid}
35
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 -- >
36
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);
}
}
37
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>
No two functions within a tag library
</taglib>
can have the same name.
</jsp-config>
38
</web-app>
JSP EL: Using EL Functions
• The previous EL functions can be used as
following:
– ${equals('string1', 'string2')}
39
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.
40
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>
41
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
42
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.
43
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.
44
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 />
<% }
}
%>
45
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>
46
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.
47
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
48
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" %>
49
Organization of JSTL
• The JSTL tags are organized into five libraries
Library features
URI
Core(control flow,
http://java.sun.com/jsp/jstl/core
URLs, variable access)
Prefix
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
50
JSTL: Core Tags
• General-purpose:
– out set catch remove
• Flow control:
– forEach forTokens
• Conditional:
– if choose when otherwise
• URL management:
– url import redirect param
51
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>
52
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/>
53
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>
54
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>
55
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" />
56
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.
57
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>
58
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>
59
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
60
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>
61
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>
62
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>
63
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>
64
JSTL Tags: <c:url>
• This tag provides automatically encoded URLs.
• Session information and parameters are encoded
with a URL.
• Example: urlDemo.jsp
65
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
66
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>
67
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" />
68
<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>
69
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>…
70
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
71
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
72
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.
73
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");
}
}
74
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.
75
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>
76
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>
77
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
78
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>
79
Learn More about JSTL
• JSTL in Action
80