Download (JSP). - Computer Science and Engineering

Document related concepts
no text concepts found
Transcript
COMP9321 Web Applications Engineering
Java Server Pages (JSP).
Service Oriented Computing Group, CSE, UNSW
Week 4
Notes prepared by Dr. Helen Hye-young Paik, CSE, UNSW.
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
1 / 77
Java ServerPages (JSP)
A problem with servlets:
HTML code is produced inside Java code
eg., out.println(“<H1>Hello folks!</H1>”);
ie., low maintainability, mixture of presentation (eg., HTML) and
business logic (eg., Java Code that extract data from tables)
The HTML is inaccessible to nonS-Java developers – If you Web app
is developed using Servlets, you will have to be an expert in
HTML/CSS as well as in Java.
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
2 / 77
Java Servet Pages (JSP)
JSP lets the programmer separate HTML coding from business logic (Java
coding).
The lifecycle of JSP is maintained by JSP container
JSP really is just a servlet (it becomes one eventually!)
JSP container converts a JSP to a servlet at runtime
Servlet container and JSP container are normally combined into one
(referred to as Web container)
writes
.................................
.................................
.................................
.................................
.................................
.................................
MyJSP.jsp
H. Paik (CSE, UNSW)
is
translated to
.................................
.................................
.................................
.................................
.................................
.................................
MyJSP_jsp.java
COMP9321, 13s2
compiles to
.................................
.................................
.................................
.................................
.................................
.................................
loaded and
initlaised as
...............
...............
...............
...............
...............
...............
...............
......
MyJSP_jsp
Servlet
MyJSP_jsp.class
Week 4
3 / 77
Java Servet Pages (JSP)
request
Web
Browser
response
<FORM>
<INPUT>
parameters...
</INPUT>
</FORM>
request
Web
Server
JSP
Container
JSP
files
response
1. Parse JSP
DB
2. Generate the
Servlet code from JSP
3. Compile the Servlet code
into a Servlet class
4. Run the Servlet
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
4 / 77
Java Servet Pages (JSP)
Parsing, generating, compiling of JSP only happens on the first request.
subsequent requests
first
request
translate
JSP
execute
Where do JSP pages go in .war
structure?
They are generally placed
under the application root
with other static content
JSPs can be mapped to
virtual URLs just like servlets
<servlet>
<servlet-name>ConfigDemo</servlet-name>
<jsp-file>/configdemo.jsp</jsp-file>
<init-param>
<param-name>WebMaster</param-name>
<param-value>Helen Paik</param-value>
</init-param>
</servlet>
Also some initial parameters
can be set in web.xml
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
5 / 77
Let us revisit the WelcomeServlet
import
import
public
{
public
javax.servlet.*;
javax.servlet.http.*;
class WelcomeServlet extends HttpServlet
void doGet (HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<HTML>");
out.println("<BODY>");
out.println("<CENTER>");
out.println("<H1>Let’s visit Australia!</H1>");
out.println("Would you like to begin your journey?");
out.println("<FORM ACTION=’MenuServlet’ METHOD=’POST’>");
out.println("<INPUT TYPE=’submit’ VALUE=’Onwards!’>");
out.println("</FORM>");
out.println("</CENTER>");
out.println("</BODY>");
out.println("</HTML>");
}
}
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
6 / 77
Here is equivalent in JSP (welcome.jsp)
<HTML>
<BODY>
<CENTER>
<H1>Let’s visit Australia!</H1>
Would you like to begin your journey?
<FORM ACTION=’menu.jsp’ METHOD=’POST’>
<INPUT TYPE=’submit’ VALUE=’Onwards!’>
</FORM>
</CENTER>
</BODY>
</HTML>
Observation:
welcome.jsp calls another JSP, menu.jsp.
No explicit import of the servlet packages
No declaration of the servlet class WelcomeServlet
No setContentType
No PrintWriter
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
7 / 77
Next let us revisit the MenuServlet
public class MenuServlet extends HttpServlet {
public void doPost (HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
HttpSession session = req.getSession(true);
if (session.getAttribute("JourneyFlag") == null) {
Journey jny= new Journey();
session.setAttribute("JourneyFlag",jny);
}
out.println("<HTML><BODY><CENTER>");
out.println("<H1>Choose a state</H1>");
out.println("<FORM Action=’ControlServlet’ METHOD=’POST’>");
out.println("<SELECT
NAME=’State’ SIZE=7>");
out.println("<OPTION>
QLD");
... snip ...
out.println("</SELECT>");
out.println("<BR><BR><INPUT type=’submit’ value=’Send’>"+
"<INPUT type=’reset’>");
out.println("</FORM>");
out.println("</CENTER></BODY></HTML>");
}
}
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
8 / 77
Here is equivalent in JSP (menu.jsp)
<%@ page import="com.comp9321.Journey" %>
<% Journey jny;
if (session.getAttribute("JourneyFlag") == null) {
jny= new Journey();
session.setAttribute("JourneyFlag",jny);
}
%>
<HTML><BODY><CENTER>
<H1>Choose a state</H1>
<FORM
Action=’control.jsp’ METHOD=’POST’>
<SELECT NAME=’State’ SIZE=7>
<OPTION>QLD
<OPTION>NSW
... snip ...
<OPTION>NZ
</SELECT>
<BR><BR>
<INPUT type=’submit’ value=’Send’>
<INPUT type=’reset’>
</FORM></CENTER></BODY></HTML>
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
9 / 77
More observations ...
Note notations like <%@ . . . %> and <% ... %>
I
<% ... signals the start of a JSP element
I
there are different kinds of JSP elements we need to look at ...
You need to import any ’custom’ classes in package form: line 1 in
menu.jsp
I
eg., Journey is in: WEB-INF/classes/com/comp9321/Journey.class
I
You must use packages to include custom classes
Typically, a JSP file consists of:
I
HTML Template (static,presentation): from line 14 in menu.jsp
I
JSP elements (dynamic, Java coding): line 1-8 in menu.jsp
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
10 / 77
JSP compiler: welcome.jsp → welcome jsp.java
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import org.apache.jasper.runtime.*;
public class welcome_jsp extends HttpJspBase {
... snip ...
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException, ServletException {
JspFactory _jspxFactory = null;
javax.servlet.jsp.PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
JspWriter _jspx_out = null;
try {
_jspxFactory = JspFactory.getDefaultFactory();
response.setContentType("text/html;charset=ISO-8859-1");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
out.write("<HTML>");
out.write("<BODY>");
..snip ..
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
11 / 77
JSP basics
page
directive
elements
include
taglib
scripting
declaration
scriptlet
expression
action
standard
JSP
custom
template (HTML bits ...)
Plus the implicit JSP objects: request, response, out, session, config, etc.
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
12 / 77
JSP Elements: JSP directives
JSP directives: gives special info. about the page to the JSP container
Syntax: <%@ directive ...%>
page directive - processing information for the page
I
I
I
I
<%@
<%@
<%@
<%@
page
page
page
page
import="java.util.*, mypackage.util" %>
errorPage="/errors/GenericError.jsp" %>
info="author: H. Paik copyright 2004" %>
session="false" %>
include directive - files to be included in the page
I
<%@ include file="footer.html" %>
I
Lets you insert a piece of text (be it JSP code or HTML code) into the
main page before the main page is translated into a servlet.
taglib directive - tag library to be used in the page
I
<%@ taglib
H. Paik (CSE, UNSW)
uri="uri-for-the-library" prefix="c" %>
COMP9321, 13s2
Week 4
13 / 77
JSP Elements: JSP Scripting (expression)
JSP expression: evaluated and converted into a string, and inserted in
the page (into the translated servlet, inside out.println(...))
Syntax: <%= expression %>
An expression must result in a String, e.g.,
I
<BODY BGCOLOR= "<%= bgColor %>">
I
<H1>Hello <%= username %> </H1>
I
Discounted price is: <bold><%= (total*0.9) %></bold>
The evaluation is performed at runtime.
I
eg., Current time: <%= new java.util.Date() %>
I
The above will display the time when the page is requested
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
14 / 77
JSP Elements: JSP Scripting (expression)
A JSP expression will be placed into out.println() in the resulting
servlet.
Random.jsp
Random jsp.java
<html>
<body>
<h1>A Random Num</h1>
<%= Math.random() %>
</body>
</html>
public class Random_jsp extends HttpJspBase ...{
public void _jspService(HttpServletRequest ...){
PrintWriter out = response.getWriter();
response.setContentType("text/html");
out.write("<html><body>");
out.write("<h1>A Random Number</h1>");
out.write(Math.random()); ... snip ...
Hence, the following will be wrong
Inside JSP
Inside Servlet JSP
<%= Math.random(); %>
out.write(Math.random();); → error
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
15 / 77
JSP Elements: Using the implicit objects
request: the HttpServletRequest object
response: the HttpServletResponse object
session : the HttpSession object associated with the request
out: the Writer object
config: the ServletConfig object
application: the ServletContext object
For example, inside jspexp.jsp:
<html><body>
<h2>JSP expressions</h2>
<ul>
<li>Current time is: <%= new java.util.Date() %>
<li>Server Info: <%= application.getServerInfo() %>
<li>Servlet Init Info: <%= config.getInitParameter("WebMaster") %>
<li>This Session ID: <%= session.getId() %>
<li>The value of <code>TestParam</code> is:
<%= request.getParameter("TestParam") %>
</ul>
</body></html>
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
16 / 77
JSP Elements: JSP Scripting (expression)
Valid or Invalid?
<%= 27 %>
<%= ((Math.random() + 5)*2; %>
<%= "27" %>
<%= Math.random() %>
<%= String s = "foo" %>
<%= 5 > 3 %>
<%= request.getParameter("choice") %>
<% =
42*20 %>
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
17 / 77
JSP Elements: JSP Scripting (scriptlet)
JSP scriptlet: inserted verbatim into the translated servlet code
Syntax: <% ... Java code ... %>
JSP scriptlet
<%
String bgColor = request.getParameter("bgColor");
boolean hasExplicitColor;
if (bgColor != null) {
hasExplicitColor = true;
} else {
hasExplicitColor = false;
}
%>
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
18 / 77
JSP Elements: JSP Scripting (scriptlet)
The following three are the same ...
One
<%
String queryData = request.getQueryString();
out.println("Query string passed in: " + queryData);
%>
Two
<% String queryData = request.getQueryString(); %>
Query string passed in: <%= queryData %>
Three
Query string passed in: <%= request.getQueryString() %>
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
19 / 77
JSP Elements: JSP Scripting (scriptlet)
Remember that JSP expressions contain ‘(string) values’, but JSP
scriptlets contain ‘Java statements’.
in JSP
<H2>Hello Foo</H2>
<%= bar() %>
<% zoo(); %>
In Servlet JSP
public void _jspService(HttpServletRequest ...) {
response.setContentType("text/html");
HttpSession session = request.getSession();
PrintWriter out = response.getWriter();
out.println("<H2>Hello Foo</H2>");
out.prinln(bar());
zoo();
}
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
20 / 77
JSP Elements: JSP Scripting (scriptlet)
(CoreServlet p.334)
Eg., setting the background of a page
background.jsp
<html>
<%
String bgColour= request.getParameter("bgColour");
if ((bgColour == null) || (bgColour.trim().equals(""))) {
bgColour = "WHITE";
}
%>
<body bgcolor="<%= bgColour %>">
<h2 align="center">Testing a Background of "<%= bgColour %>"</h2>
</body>
</html>
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
21 / 77
JSP Elements: JSP Scripting (scriptlet)
You can also use the scriptlet to conditionally generate HTML.
passfail.jsp
<html><body>
<% if (Math.random() < 0.5) { %>
<h1>My prediction is that you will pass COMP9321</h1>
<% } else { %>
<h1>My prediction is that you will fail COMP9321</h1>
<% } %>
</body></html>
code inside a scriptlet is inserted into the servlet jsp
static HTML before and after a scriptlet goes inside out.prinln()
the above becomes ...
if (Math.random() < 0.5) {
out.println("<h1>My prediction is that you will pass COMP9321</h1>");
} else {
out.println("<h1>My prediction is that you will fail COMP9321</h1>");
}
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
22 / 77
JSP Elements: JSP Scripting (comment)
JSP comment: Developers’ comments that are not sent to the client page
Syntax: <%-- Blah --%>
Eg., <%-- This needs to be fixed. A bug found --%>
Eg., <!-- This needs to be fixed. A bug found --!>
HTML comments are shown to the clients in the resultant page.
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
23 / 77
Finally, let us revisit the EnoughServlet
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class EnoughServlet extends HttpServlet {
public void doPost (HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
HttpSession session = req.getSession(true);
session.invalidate();
out.println("<HTML>");
out.println("<BODY>");
out.println("<CENTER>");
out.println("<H1>No longer in session!</H1>");
out.println("<FORM Action=’WelcomeServlet’ METHOD=’GET’>");
out.println("<INPUT type=’submit’ value=’Try it’>");
out.println("</FORM>");
out.println("</CENTER>");
out.println("</BODY>");
out.println("</HTML>");
}
}
//end of EnoughServlet
Exercise: Let’s write the code for the JSP file enough.jsp.
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
24 / 77
Request attributes and RequestDispatcher
We use request attributes when you want some other component of the
application take over all or part of your request. This typically occurs
between Servlets and JSPs in the MVC model.
// code inside doGet()
String postcode = getPostcode(request.parameter("suburb");
request.setAttribute("pc", postcode);
RequestDispatcher view =
request.getRequestDispatcher("DisplayPostcode.jsp");
view.forward(request, response);
// DisplayPostcode.jsp will use the request attribute pc to
// access the postcode and present it nicely.
There is no reason to use context or session attributes, since it only applies
to this request (so request scope is enough).
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
25 / 77
Attributes in a JSP
(HeadFirst) p.309
Application scope
I
I
servlet: getServletContext().setAttribute(“foo”, barObj);
jsp: application.setAttribute(“foo”, barObj);
Request scope
I
I
servlet: request.setAttribute(“foo”, barObj);
jsp: request.setAttribute(“foo”, barObj);
Session scope
I
I
servlet: request.getSession().setAttribute(“foo”, barObj);
jsp: session.setAttribute(“foo”, barObj);
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
26 / 77
JSP Elements: JSP Actions
JSP standard action: dynamic behaviour of the page
Syntax: <jsp:action-name />
<jsp:include page="next.jsp" />
<jsp:forward page="next.jsp" />
<jsp:useBean ... />
<jsp:setProperty ... />
<jsp:getProperty ... />
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
27 / 77
JSP Elements: JSP Actions (include)
jsp:include action: lets you include the output of a page at request time.
Any changes in the ’included’ page can be picked up without changing the
main page. You can include:
The content of an HTML page
The content of a plain text document
the output of JSP page
the output of a servlet
Note: you cannot include JSP code (unlike include directive). The
behaviour is the same as RequestDispatcher.include()
include header and footer
<jsp:include page="/common/header.jsp"/>
... some more jsp code ...
<jsp:include page="/common/footer.jsp"/>
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
28 / 77
jsp:include vs. include directive
Syntax?
When does inclusion occur?
What is included?
How
many
servlets result?
maintenance?
H. Paik (CSE, UNSW)
(CoreServlet p.380)
jsp:include action
<jsp:include page= .../>
Request time
include directive
<%@ include file= %>
Page translation time
Output of the included
page
More than one (main
page, and one for each included page)
Actual content of file
changes in included pages
does not require recompilation of the main page
COMP9321, 13s2
One (included file is inserted into the main
page, then the page is
translated)
the main page needs to
be recompiled when the
included page changes
Week 4
29 / 77
JSP Elements: JSP Actions (forward)
jsp:forward action has the same behaviour as RequestDispatcher.forward().
jsp forwarding
<% String destination;
if (Match.random() > 0.5) {
destination = "/examples/page1.jsp";
} else {
destination = "/examples/page2.jsp";
}
%>
<jsp:forward page="<%= destination %>" />
To use JSP forward, the main page cannot commit any output to the
client (same as RequestDispatcher.forward()).
It is generally recommended that ’dispatching’ tasks to be done using
RequestDispatcher.forward(), rather than JSP ...
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
30 / 77
JSP Elements: JSP Actions (useBean)
Can you imagine implementing everything about your application in JSP?
Using separate Java classes is easier to compile, test, debug and reuse.
JSP actions provide strong support using beans in JSP.
A bean is an object with
private properties
setWeight()
getWeight()
Person(){}
weight
setHeight()
getHeight()
height Person
name
setName()
getName()
Access to a JavaBean is
strictly through “set” or
“get” methods
the setter and getter
methods follow a naming
convention ...
hairColour
setHairColour()
getHairColour()
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
31 / 77
JSP Elements: JSP Actions (useBean)
Basics of using beans: through JSP actions (useBean, get/setProperty)
jsp:useBean: creates a new instance of a bean
<jsp:useBean id="beanName" class="package.Class" />
jsp:getProperty: reads and outputs the value of a bean property (ie.,
calling a getter method)
<jsp:getProperty name="beanName"
property="propertyName" />
jsp:setProperty: modifies a bean property (ie., calling a setter
method)
<jsp:setProperty
name="beanName"
property="propertyName"
value="propertyValue" />
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
32 / 77
JSP Elements: JSP Actions (useBean)
<jsp:useBean id="customer" class="enterprise.com.Customer" />
A few things about using beans:
the above example reads “instantiate an object of the class
’enterprise.com.Cusomer’ and bind it to the variable specified by id.”
The customer variable is created inside the service() method – ie.,
local variable.
You must use the fully qualified class name in the class attribute
(even if you use <%@ page import ...%>.
the JavaBean classes can be placed under:
I
I
WEB-INF/classes/appropriate package directories/
WEB-INF/lib/inside jar files
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
33 / 77
Sharing Beans: using scope attribute
When jsp:useBean instantiates a bean, you can ask the container to
share it across various scopes.
That is achieved by storing the bean in different locations: page only,
request, session or the servlet context
The Web container looks for an existing bean of the specified name in
the designated location. If it fails to locate the bean in the location,
it creates a new instance, otherwise, use the existing instance.
It is generally recommended that you use different variable names (ie.,
id attribute) for different scopes.
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
34 / 77
Sharing Beans: using scope attribute
<jsp:useBean ... scope=”page” />: this is the default value. The
beans are not shared. Thus a new bean is created for each request.
<jsp:useBean ... scope=”request” />: the bean is bound to the
HttpServletRequest object and the bean is shared for the duration of
the current request (eg., forwarding).
<jsp:useBean ... scope=”session” />: the bean is bound to the
HttpSession object associated with the current request.
<jsp:useBean ... scope=”application” />: the bean is bound to
the ServletContext (ie., the bean is shared by all JSP pages in the
application).
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
35 / 77
Using JSP actions
Using JSP action tags appropriately can simplify the coding exercises ...
beanBasicsAction.jsp
<HTML><HEAD><TITLE>beanBasics Action</TITLE></HEAD>
<BODY>
<%
styler bob = new styler();
bob.setFontsize(request.getParameter("size");
bob.setColour(request.getParameter("colour");
bob.setWord(request.getParameter("word"); %>
<P STYLE="font-size:<%=bob.getFontsize()%>; color:<%=bob.getColour()%>;">
Capital is <%= bob.hasCapital() %> !! </P>
Using JSP actions, you can use JavaBeans from a JSP without having
to use <% ... %>. i.e., you can hide Java from HTML
beanBasicsAction.jsp
<HTML><HEAD><TITLE>beanBasics Action</TITLE></HEAD>
<BODY>
<jsp:useBean id="bob" scope="request" class="beans.styler"/>
<jsp:setProperty name="bob" property="*"/>
</BODY></HTML>
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
36 / 77
Expression Language (EL) in JSP
A few things about JSP useBean, set/getProperty
verbose and clumsy (eg., easy to miss a closing tag) - XML Syntax.
accessing subproperties is not supported
Subproperty example
(Headfirst) p.364
Person has a String “name” property
Person has a Dog “dog” property
Dog has a String “name” property
In a servlet ...
public void doPost ( ...) {
foo.Person p = new foo.Person();
p.setName("Evan");
foo.Dog dog = new foo.Dog();
dog.setName("Spike");
p.setDog(dog);
request.setAttribute("person", p);
RequestDispatcher view = request.getRequestDispatcher("result.jsp");
view.forward(request, response);
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
37 / 77
Towards Scriptless JSP
what if you want to print the name of the Person’s dog in result.jsp?
In result.jsp ...
<HTML><BODY>
<jsp:useBean id="person" class="foo.person" scope="request"/>
My dog is: <jsp:getProperty name="person" property="dog"/>
</BODY></HTML>
What you get is:
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
38 / 77
Towards Scriptless JSP
JSP 2.0 even more simplifies the way you access Java code using JSP
Expression Language (EL)
Assuming that person is stored in a scope location, the previous code can
now be:
<HTML><BODY>
My dog is: ${person.dog.name}
</BODY></HTML>
Note: person needs no declaration here ...
JSP 2.0 expression language lets you simplify writing JSP by replacing
scripting elements as well as useBean, get/setProperty actions.
${ expression }
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
39 / 77
Expression Language (EL)
The first named variable in
the expression is either an implicit object
or an attribute
${firstThing.secondThing}
Attribute
EL Implicit Object
pageScope
requestScope
sessionScope
applicationScope
attribute objects
in page scope
in request scope
in session scope
in application scope
param
paramValues
header
headerValues
cookie
(HeadFIrst) p.367
initParam
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
40 / 77
Expression Language (EL)
Easy access to the stored attributes
I
eg., session.setAttribute(”subscription”, ”Monthly”)
I
Your subscription choice is: ${subscription}
Easy access to bean properties (shorthands)
I
${person.name}, ${person.dog.name}
Easy access to collections
I
accessing array or List or Map (eg., ${orderItems[0]})
EL implicit objects (besides the JSP implicit objects)
Automatic type conversion (string to number)
Null handling (empty value instead of an error message)
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
41 / 77
EL Basics: Accessing Scoped Variables
Scoped Variables (or Attributes): Any name-value pair attributes stored
in one of the four locations can be accessed:
HttpServletRequest object (request)
HttpSession object (session)
ServletContext object (application)
PageContext object (page – not shared)
In each of the location, you could use setAttribute()/getAttriute() to
store/retrieve the name-value attribute pairs. EL gives you an easy way to
access these scoped vaiables.
Eg.,
request.setAttribute("customerLocation", "Australia"); // a String
request.setAttribute("ShoppingCart", cart); // an object
<B>You are shopping from: ${customerLocation}</B>
<B>Total price is: ${ShoppingCart.total}</B>
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
42 / 77
EL Basics: Accessing Scoped Variables
Note that you do not have to specify the scope of the variable in the
expression.
The attribute name in the expression (${attribute name}) is searched
in all four locations
Search order: PageContext → HttpServletRequest → HttpSession →
ServletContext
Choose unique names for the attribute if you don’t want the container
to be confused, or return a unexpected answer ...
<%
request.setAttribute("name","Koala in Request");
session.setAttribute("name2","Koala in Session");
application.setAttribute("name3","Koala in Application");
request.setAttribute("sameName","Koala in Request");
session.setAttribute("sameName","Koala in Session");
application.setAttribute("sameName","Koala in Application");
%>
What will be the result of printing name, name2, name3 and sameName?
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
43 / 77
EL Basics: Using dot vs. Using [ ] operator
left must be a Map or a bean
(Headfirst) p.368
${person.name}
java.util.Map
a bean
right must be a Map key or a bean property
${person.name}
getName()
or setName()
"name", "Evan"
java.util.Map
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
44 / 77
EL Basics: Using dot vs. Using [ ] operator
Using dot operator: If the expression has a variable followed by a dot (.),
${person.name}
the left-hand variable must always be a java.util.Map or a bean.
(ie., something with a key, or something with properties)
The right-hand variable must be a Map key or a bean property
The right-hand variable must be a Java name
I
cannot start with a number
I
cannot be a Java keyword
I
no spaces
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
45 / 77
EL Basics: Using dot vs. Using [ ] operator
(Headfirst) p.374
In a servlet
java.util.Map musicMap = new java.util.HashMap();
musicMap.put("Ambient", "Zero 7");
musicMap.put("Surf", "Tahiti 80");
musicMap.put("Indie", "Travis");
request.setAttribute("musicMap", musicMap);
In a JSP
Ambient is: ${musicMap.Ambient}
The JSP will print Zero 7
For beans and Maps, using dot (.) operator is good enough. In fact, the
following two are the same in a bean.
${person.name} or ${person[“name”]}
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
46 / 77
EL Basics: Using dot vs. Using [ ] operator
left can be a Map, a bean, a List or an array
${musicList["something"]}
java.util.Map
a bean
(Headfirst) p.370
java.util.List
an array
right must be a Map key or a bean property
or an index of a List or an array (e.g., a number)
${musicList["something"]}
"dance", "Gotye"
1: "Zero 7",
2: "Chemical Romance"
1: "Zero 7",
2: "Chemical Romance"
getSongList()
setSongList()
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
47 / 77
EL Basics: Using dot vs. Using [ ] operator
Using [ ] operator: If EL has a variable followed by a bracket [ ],
the left-hand variable can be a java.util.Map, a bean, a List or an
array
The value inside[ ] can be a Map key or a bean property, or an index
into a List or array
Something about the value inside [ ] ...
The value can be a string literal (ie., “value”)
I
${musicMap[“Ambient”]}
If there are no quotes, the value is evaluated
I
I
I
${musicMap[Ambient]}
→ finds an attribute named Ambient. Use the value of that attribute
as the key into the Map, or return null
there is no attribute called Ambient in any of the scopes, so this does
not work.
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
48 / 77
EL Basics: Using dot vs. Using [ ] operator
In a servlet
java.util.Map musicMap = new java.util.HashMap();
musicMap.put("Ambient", "Zero 7");
musicMap.put("Surf", "Tahiti 80");
musicMap.put("Indie", "Travis");
request.setAttribute("musicMap", musicMap);
request.setAttribute("Genre", "Ambient");
Which one of the followings would work?
Without quotes
Ambient is: ${musicMap[Genre]}
With quotes
Ambient is: ${musicMap[‘‘Genre’’]}
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
49 / 77
EL Basics: Using dot vs. Using [ ] operator
You can use nested expressions inside the brackets.
In a servlet
java.util.Map musicMap = new java.util.HashMap();
musicMap.put("Ambient", "Zero 7");
musicMap.put("Surf", "Tahiti 80");
musicMap.put("Indie", "Travis");
request.setAttribute("musicMap", musicMap);
String[] musicTypes = {"Ambient", "Surf", "Indie"};
request.setAttribute("MusicType", musicTypes);
Expression inside [ ]
Ambient is: ${musicMap[MusicType[0]]}
${musicMap[MusicType[0]]} → ${musicMap[”Ambient”]} → Zero 7
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
50 / 77
EL Basics: Using dot vs. Using [ ] operator
[ ] operator gives you a uniform way of accessing collections.
Also, the dot operator requires you to know the key/property in advance.
But the [ ] operator can accept a variable that will be evaluated at runtime
(because the unquoted values inside [ ] are evaluated).
Some java code
<% String[] firstNames={"Bill", "Steve", "Larry"};
ArrayList lastNames = new ArrayList();
lastNames.add("Ellison");
lastNames.add("Gates");
lastNames.add("Jobs");
HashMap companyNames = new HashMap();
companyNames.put("Ellison", "Oracle");
companyNames.put("Gates", "Microsoft");
companyNames.put("Jobs", "Apple Inc.");
request.setAttribute("first", firstNames);
request.setAttribute("last", lastNames);
request.setAttribute("company", companyNames); %>
<jsp:include page="display names.jsp"/>
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
51 / 77
EL Basics: Using dot vs. Using [ ] operator
display names.jsp
<HTML><BODY>
<H2>Accessing Collections with EL</H2>
<P/>
<UL>
<LI>${first[0]} ${last[0]} (${company["Ellison"]})</LI>
<LI>${first[1]} ${last[1]} (${company["Gates"]})</LI>
<LI>${first[2]} ${last[2]} (${company["Jobs"]})</LI>
</UL>
</BODY></HTML>
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
52 / 77
EL Basics: EL Implicit Objects
EL provides its own implicit objects (most of them are Maps)1 .
param and paramValues:
let you access the primary request parameter (param)
or the array of request parameter values (paramValues)
header and headerValues:
let you access the primary and complete HTTP request header values
Some of the value names must be enclosed with [ ] (eg.,
“User-Agent”)
initParam:
let you access context initialisation parameters
1
Not to be confused with JSP implicit objects.
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
53 / 77
EL Basics: EL Implicit Objects
cookies:
let you reference incoming cookies.
The return value is the Cookie object. This means yo access the
value, you have to use value property (ie., getValue() method)
pageScope, requestScope, sessionScope and applicationScope:
These object let you restrict where the system looks for scoped
variable
eg., ${requestScope.name} only looks into HttpServletRequest
pageContext:
object (not a Map) that represents current page
This object has request, response, session, and servletContext
properties
eg., ${pageContext.session.id}
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
54 / 77
EL Basics: EL Implicit Objects
el implicit.jsp
<HTML><BODY>
<H2>Using EL implicit objects</H2>
<P/>
<UL>
<LI><b>Request parameter called <code>test</code>:</b> ${param.test}</LI>
<LI><b>User-agent info in request Header:</b> ${header["User-Agent"]}</LI>
<LI><b>Cookie (JSESSIONID) value:</b> ${cookie.JSESSIONID.value}</LI>
<LI><b>Server Info:</b> ${pageContext.servletContext.serverInfo}</LI>
<LI><b>Request Method:</b> ${pageContext.request.method}</LI>
</UL>
</BODY></HTML>
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
55 / 77
EL Basics: EL Operators
Category
Arithmetic
Relational
Logical
Validation
Operators
+, -, *, / (or div), % (or mod)
== (or eq), != (or ne), <(or lt), > (or gt),
<= (or le), >= (or ge)
&& (or and), || (or or), ! (or not)
empty
${item.price * (1 + taxRate[user.address.zipcode])}
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
56 / 77
JSP Standard Tag Library (JSTL)
With JSP actions and EL, you could remove bulk of scripting
elements from JSP. However, you may need more functionality,
something beyond what you can get with JSP actions and EL.
Imagine that your JSP is expecting a userName parameter. If it
doesn’t exist, you want to call another JSP that will ask for userName
from the user. That is, you want to check for some conditions ...
You may have to resort to scripting again ...
e.g., Hello.jsp and CollectName.jsp in the next slide.
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
57 / 77
JSP Standard Tag Library (JSTL)
Hello.jsp
<html><body>
Welcome to your page!
<% if (request.getParameter("userName") == null) { %>
<jsp:forward page="CollectName.jsp"/>
<% } %>
Hello ${param.userName}
</body></html>
CollectName.jsp
<html><body>
We are sorry ... you need to log in again.
<form action"Hello.jsp" method="get">
Name: <input name="userName" type="text">
<input name="Submit" type="submit">
</form>
</body></html>
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
58 / 77
JSP Standard Tag Library (JSTL)
JSP provides a set of tag library for performing tasks that are
common in programming
With JSTL and EL, you can do just about everything without using
JSP scripting elements
Here is how you might handle the conditional forward with JSTL
(Hello.jsp and CollectName.jsp)
Hello.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html><body>
Welcome to your page!
<c:if test="${empty param.userName}" >
<jsp:forward page="CollectName.jsp"/>
</c:if>
Hello ${param.userName}
</body></html>
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
59 / 77
JSP Standard Tag Library (JSTL)
The JSTL consists of the following major libraries.
Core: (programming-like) actions.
<%@taglib uri="http://java.sun.com/jstl/core" prefix="c"%>
Fmt: Formatting and internationalisation.
<%@taglib uri="http://java.sun.com/jstl/fmt" prefix="fmt"%
SQL: SQL database actions.
<%@taglib uri="http://java.sun.com/jstl/sql" prefix="sql"%
XML: XML processing actions.
<%@taglib uri="http://java.sun.com/jstl/x" prefix="x"%>
http://java.sun.com/products/jsp/jstl/
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
60 / 77
JSP Standard Tag Library (JSTL)
Installing JSTL libraries: JSTL 1.1 is not part of the JSP specification.
Before you could use JSTL, you need to install two files:
standard.jar
jstl.jar
They need to be placed under WEB-INF/lib
Note: the lab exercise files contain these two (labXX/libs). The build.xml
file already has instructions which copy the two JAR files to the
WEB-INF/lib directory.
The specification:
http://jcp.org/aboutJava/communityprocess/final/jsr052/
index2.html
J2EE 1.4 SDK includes JSTL 1.1 implementation.
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
61 / 77
JSTL Basics: Looping collections
In a servlet
...
String[] movieList={"Amelie", "Return of the King", "Mean Girls"};
request.setAttribute("movieList", movieList);
...
Say you want to print the array content in an HTML table.
Using JSP scripting, you would do ...
<table>
<% String[] items= (String[]) request.getAttribute("movieList");
String movie = null;
for (int i=0; i < items.length; i++) {
movie = items[i];
%>
<tr><td><%= var %></td></tr>
<% } %>
</table>
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
62 / 77
JSTL Basics: Looping collections
In a servlet
...
String[] movieList={"Amelie", "Return of the King", "Mean Girls"};
request.setAttribute("movieList", movieList);
...
Using JSTL, you would do ...
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<table>
<c:forEach var ="movie" items="${movieList}">
<tr><td>${movie}</td></tr>
</c:forEach>
</table>
The above loops through the entire movieList array (ie., movieList
attribute) and print each element.
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
63 / 77
JSTL Basics: Looping collections
(HeadFirst) p.438
The variable that holds
each element
in the collection.
It's value changes with each iteration
Thing to loop over
(Array, Collection, Map)
<c:forEach var ="movie" items="${movieList}">
<tr><td>${movie}</td></tr>
</c:forEach>
String[] items= (String[]) request.getAttribute("movieList");
for (int i=0; i < items.length; i++) {
String movie = items[i];
out.println(movie);
}
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
64 / 77
JSTL Basics: Conditional output
Assuming that attributes commentList and memberType are set
previously ...
JSTL <c:if>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html><body>
<ul>
<c:forEach var ="comment" items="${commentList}">
<li>${comment}</li>
</c:forEach>
</ul>
<hr>
<c:if test="${memberType eq ’full access’}">
<strong>Add your comments</strong>
<form action="postcomment.jsp" method="post">
<textarea name="input" cols="40" rows="10"></textarea>
<input name="postcomment" type="button" value="add comment">
</form>
</c:if>
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
65 / 77
JSTL Basics: Conditional output
There is no ELSE construct in JSTL. To check for multiple tests, you will
use:2
c:choose, c:when and c:otherwise
<c:choose>
<c:when test="${pageContext.request.scheme eq ’http’}">
This is an insecure Web session.
</c:when>
<c:when test="${pageContext.request.scheme eq ’https’}">
This is a secure Web session.
</c:when>
<c:otherwise>
You are using an unrecognized Web protocol. How did this happen?!
</c:otherwise>
</c:choose>
2
http:
//www-128.ibm.com/developerworks/java/library/j-jstl0318/
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
66 / 77
JSTL Basics: Using <c:set>
<c:set> tag comes in two flavours: var and target
<c:set var="userLevel" scope="session" value="full access" />
<c:set var="Fido" scope="request" value="$person.dog" />
The above sets an attribute in a scope (i.e., like setAttribute() method)
<c:set target="${PetMap}" property="dogName" value="Fido" />
<c:set target="${person}" property="name" value="Evan" />
The above sets a Map value and a property of a bean, respectively.
i.e.,
person is a bean and its name property is set to ’Evan’
PetMap is a Map and the value of a key named dogName is set to
Fido.
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
67 / 77
JSTL Basics: Using <c:set>
A few things to note about using <c:set>.
Take,
<c:set var="Fido" scope="request" value="${person.dog}" />
scope is optional, default is page scope
If the value evaluates to null, the attribute Fido will be removed from
the scope
The attribute Fido does not exist, it will be created (only if value is
not null).
Take,
<c:set target="${person}" property="name" value="Evan" />
The target must an expression which evaluates to the Object (not the
String ’id’ name of the bean or Map)
If the target expression is null, the container throws an exception
If the target expression is not a Map or a bean, the container throws
an exception
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
68 / 77
JSTL Basics: Working with URL
<c:set var="last" value="William Bush"/>
<c:set var="first" value="George"/>
<c:url value=”/nextpage.jsp?first=${first}&last=${last}” var=”nextURL”/>
What about the space in “William Bush”?
<c:url value="/nextpage.jsp" var="nextURL">
<c:param name="fisrt" value="${first}"/>
<c:param name="last" value="${last}"/>
</c:url>
Using <c:param> takes care of URL encoding:
http://localhost:8080/MyApp/nextpage.jsp?first=George&last=William+Bush
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
69 / 77
Other things available in JSTL
Core
<c:out>
<c:catch>
<c:redirect>
<c:import>
<c:remove>
<c:out>
...
Formatting tools
<fmt:formatNumber>
<fmt:parseDate>
<fmt:setTimeZone>
<fmt:parseNumber>
<fmt:setLocale>
<fmt:message>
...
XML tools
<x:parse>
<x:forEach>
<x:transform>
<x:param>
<x:if>
<x:out>
...
Easy to learn ... lots of resources online ... some of them in the
MessageBoard.
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
70 / 77
JSP Custom Tags
Tags are understood by a program that ’reads’ them; ie., the program
knows what to do with tags.
– eg., HTML tags are understood by browsers:
<A HREF="index.html">My Home Page</A>
<BOLD>Assignment Due Date</BOLD>
General Syntax:
<TagName attributeName="attValue">Body Text</TagName>
JSP allows you to create your own tags.
The behaviour of a custom tag is implemented by a Java class.
When the JSP engine encounters a custom tag, it executes the Java
code that implements the behaviour.
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
71 / 77
JSP Custom Tags
In JSP
<html><body>
<greet:hello form="brief"/>
Java Code for <greet:hello/>
</body></html>
doStartTag() {
if (form.equals="brief")
out.print("Hi ...");
return SKIP_BODY;
....
In Browser
(after running the JSP)
<html><body>
Hi ...
</body></html>
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
72 / 77
JSP Custom Tags
Consider the following JSP hello.jsp :
<%@ taglib uri="http://www.ectech.info/greetings/HelloTag"
prefix="greet" %>
<html>
<title>Greetings!</title>
<body>
<greet:hello form="brief"/>John<br/>
<greet:hello form="effusive"/>Marvin<br/>
<greet:hello form="serious"/>Kelly<br/>
<greet:hello form="serious"/>Mr Mustard<br/>
<greet:hello form="effusive"/>Georgina<br/>
</body>
</html>
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
73 / 77
JSP Custom Tags
The custom tag is declared in greetings.tld (Tag Library Descriptor):
<?xml version="1.0" encoding="ISO-8859-1" ?>
... snip ..
<taglib><tlibversion>1.0</tlibversion>
<jspversion>1.1</jspversion>
<shortname>greet</shortname>
<uri>http://www.ectech.info/greetings/HelloTag</uri>
<info>Ways of saying hello.</info>
<tag>
<name>hello</name>
<tagclass>hello.HelloTag</tagclass>
<bodycontent>empty</bodycontent>
<info>Say hello.</info>
<attribute>
<name>form</name>
<required>true</required>
</attribute>
</tag>
</taglib>
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
74 / 77
JSP Custom Tags
Actions associated with the tags are implemented: HelloTag.java
package hello;
import
import
import
import
import
java.io.IOException;
javax.servlet.jsp.PageContext;
javax.servlet.jsp.JspException;
javax.servlet.jsp.JspTagException;
javax.servlet.jsp.tagext.TagSupport;
public class HelloTag extends TagSupport {
String form;
public int doStartTag() throws JspException {
try { String greeting=null;
if (form.equals("brief")) greeting="Hi";
if (form.equals("effusive")) greeting="My dearest";
if (form.equals("serious")) greeting="Now look here";
pageContext.getOut().print(greeting+" ");
} catch(IOException ioe) {
throw new JspTagException("HelloTag error.");
}
return SKIP_BODY;
}
public void setForm(String inForm) { form = inForm; }
}
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
75 / 77
JSP Custom Tags
The web.xml file needs to know about the custom tag:
... snip ...
<web-app>
<taglib>
<taglib-uri>
http://www.ectech.info/greetings/HelloTag
</taglib-uri>
<taglib-location>
/WEB-INF/greetings.tld
</taglib-location>
</taglib>
</web-app>
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
76 / 77
the tag
JSP that uses
" %>
<html><body> "mine" uri="randomThings
x=
efi
pr
ib
gl
ta
<%
Advis
orTag
Hand
ler cl
void do
ass
Tag() {
// tag im
plemen
tation
}
r>
Advisor Page<b
void setU
se
erName}/>
us
this.use r(String user) {
${
="
er
us
ce
vi
r
ad
e:
= user;
in
<m
}
l>
</body></htm
TLD file
<taglib ...>
<uri>randomThings</uri>
<tag>
<name>advice</name>
<tag-class>foo.AdvisorTagandler</tag-class>
<body-content>empty</body-conent>
<attribute>
<name>user</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
(Headfirst) p.473
</tag>
H. Paik (CSE, UNSW)
COMP9321, 13s2
Week 4
77 / 77