COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web...

77
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

Transcript of COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web...

Page 1: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

COMP9321 Web Applications EngineeringJava 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

Page 2: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

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) andbusiness logic (eg., Java Code that extract data from tables)

The HTML is inaccessible to nonS-Java developers – If you Web appis developed using Servlets, you will have to be an expert inHTML/CSS as well as in Java.

H. Paik (CSE, UNSW) COMP9321, 13s2 Week 4 2 / 77

Page 3: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

Java Servet Pages (JSP)

JSP lets the programmer separate HTML coding from business logic (Javacoding).

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 MyJSP_jsp.java

.................................

.................................

.................................

.................................

.................................

.................................

is translated to

.................................

.................................

.................................

.................................

.................................

.................................

compiles to

...............

...............

...............

...............

...............

...............

...............

......

loaded andinitlaised as

MyJSP_jsp.class MyJSP_jspServlet

H. Paik (CSE, UNSW) COMP9321, 13s2 Week 4 3 / 77

Page 4: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

Java Servet Pages (JSP)

1. Parse JSP

2. Generate theServlet code from JSP

3. Compile the Servlet code into a Servlet class

4. Run the Servlet

WebBrowser

<FORM><INPUT>

parameters...</INPUT></FORM>

WebServer

JSPContainer

JSP files

DB

request

response

request

response

H. Paik (CSE, UNSW) COMP9321, 13s2 Week 4 4 / 77

Page 5: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

Java Servet Pages (JSP)

Parsing, generating, compiling of JSP only happens on the first request.

subsequent requestsfirst

request JSP translate execute

Where do JSP pages go in .warstructure?

They are generally placedunder the application rootwith other static content

JSPs can be mapped tovirtual URLs just like servlets

Also some initial parameterscan be set in web.xml

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

H. Paik (CSE, UNSW) COMP9321, 13s2 Week 4 5 / 77

Page 6: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

Let us revisit the WelcomeServlet

import javax.servlet.*;import javax.servlet.http.*;public class WelcomeServlet extends HttpServlet{public 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

Page 7: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

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

Page 8: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

Next let us revisit the MenuServletpublic 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

Page 9: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

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

Page 10: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

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

Page 11: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

JSP compiler: welcome.jsp → welcome jsp.javaimport 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

Page 12: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

JSP basics

elements

template (HTML bits ...)

directive

scripting

action

page

include

taglib

declaration

scriptlet

expression

standard

custom

JSP

Plus the implicit JSP objects: request, response, out, session, config, etc.

H. Paik (CSE, UNSW) COMP9321, 13s2 Week 4 12 / 77

Page 13: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

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 <%@ page import="java.util.*, mypackage.util" %>I <%@ page errorPage="/errors/GenericError.jsp" %>I <%@ page info="author: H. Paik copyright 2004" %>I <%@ page 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 themain page before the main page is translated into a servlet.

taglib directive - tag library to be used in the page

I <%@ taglib uri="uri-for-the-library" prefix="c" %>

H. Paik (CSE, UNSW) COMP9321, 13s2 Week 4 13 / 77

Page 14: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

JSP Elements: JSP Scripting (expression)

JSP expression: evaluated and converted into a string, and inserted inthe 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

Page 15: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

JSP Elements: JSP Scripting (expression)

A JSP expression will be placed into out.println() in the resultingservlet.

Random.jsp<html>

<body>

<h1>A Random Num</h1>

<%= Math.random() %>

</body>

</html>

Random jsp.java

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

<%= Math.random(); %>

Inside Servlet JSP

out.write(Math.random();); → error

H. Paik (CSE, UNSW) COMP9321, 13s2 Week 4 15 / 77

Page 16: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

JSP Elements: Using the implicit objects

request: the HttpServletRequest objectresponse: the HttpServletResponse objectsession : the HttpSession object associated with the requestout: the Writer objectconfig: the ServletConfig objectapplication: 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

Page 17: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

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

Page 18: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

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

Page 19: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

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

Page 20: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

JSP Elements: JSP Scripting (scriptlet)

Remember that JSP expressions contain ‘(string) values’, but JSPscriptlets contain ‘Java statements’.

in JSP<H2>Hello Foo</H2>

<%= bar() %>

<% zoo(); %>

In Servlet JSPpublic 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

Page 21: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

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

Page 22: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

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

Page 23: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

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

Page 24: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

Finally, let us revisit the EnoughServletimport 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

Page 25: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

Request attributes and RequestDispatcher

We use request attributes when you want some other component of theapplication take over all or part of your request. This typically occursbetween 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 appliesto this request (so request scope is enough).

H. Paik (CSE, UNSW) COMP9321, 13s2 Week 4 25 / 77

Page 26: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

Attributes in a JSP (HeadFirst) p.309

Application scope

I servlet: getServletContext().setAttribute(“foo”, barObj);I jsp: application.setAttribute(“foo”, barObj);

Request scope

I servlet: request.setAttribute(“foo”, barObj);I jsp: request.setAttribute(“foo”, barObj);

Session scope

I servlet: request.getSession().setAttribute(“foo”, barObj);I jsp: session.setAttribute(“foo”, barObj);

H. Paik (CSE, UNSW) COMP9321, 13s2 Week 4 26 / 77

Page 27: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

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

Page 28: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

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 themain 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). Thebehaviour 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

Page 29: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

jsp:include vs. include directive (CoreServlet p.380)

jsp:include action include directiveSyntax? <jsp:include page= .../> <%@ include file= %>

When does in-clusion occur?

Request time Page translation time

What is in-cluded?

Output of the includedpage

Actual content of file

How manyservlets result?

More than one (mainpage, and one for each in-cluded page)

One (included file is in-serted into the mainpage, then the page istranslated)

maintenance? changes in included pagesdoes not require recompi-lation of the main page

the main page needs tobe recompiled when theincluded page changes

H. Paik (CSE, UNSW) COMP9321, 13s2 Week 4 29 / 77

Page 30: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

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 theclient (same as RequestDispatcher.forward()).

It is generally recommended that ’dispatching’ tasks to be done usingRequestDispatcher.forward(), rather than JSP ...

H. Paik (CSE, UNSW) COMP9321, 13s2 Week 4 30 / 77

Page 31: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

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.

setName()getName()

Person(){}

setHairColour()getHairColour()

setWeight()getWeight()

Person

hairColour

height

weight

namesetHeight()getHeight()

A bean is an object withprivate properties

Access to a JavaBean isstrictly through “set” or“get” methods

the setter and gettermethods follow a namingconvention ...

H. Paik (CSE, UNSW) COMP9321, 13s2 Week 4 31 / 77

Page 32: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

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

<jsp:setProperty

name="beanName"

property="propertyName"

value="propertyValue" />

H. Paik (CSE, UNSW) COMP9321, 13s2 Week 4 32 / 77

Page 33: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

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 WEB-INF/classes/appropriate package directories/I WEB-INF/lib/inside jar files

H. Paik (CSE, UNSW) COMP9321, 13s2 Week 4 33 / 77

Page 34: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

Sharing Beans: using scope attribute

When jsp:useBean instantiates a bean, you can ask the container toshare 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 inthe 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

Page 35: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

Sharing Beans: using scope attribute

<jsp:useBean ... scope=”page” />: this is the default value. Thebeans are not shared. Thus a new bean is created for each request.

<jsp:useBean ... scope=”request” />: the bean is bound to theHttpServletRequest object and the bean is shared for the duration ofthe current request (eg., forwarding).

<jsp:useBean ... scope=”session” />: the bean is bound to theHttpSession object associated with the current request.

<jsp:useBean ... scope=”application” />: the bean is bound tothe ServletContext (ie., the bean is shared by all JSP pages in theapplication).

H. Paik (CSE, UNSW) COMP9321, 13s2 Week 4 35 / 77

Page 36: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

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

Page 37: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

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” propertyPerson has a Dog “dog” propertyDog 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

Page 38: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

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

Page 39: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

Towards Scriptless JSP

JSP 2.0 even more simplifies the way you access Java code using JSPExpression Language (EL)

Assuming that person is stored in a scope location, the previous code cannow 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 replacingscripting elements as well as useBean, get/setProperty actions.

${ expression }

H. Paik (CSE, UNSW) COMP9321, 13s2 Week 4 39 / 77

Page 40: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

Expression Language (EL)

(HeadFIrst) p.367

The first named variable inthe expression is either an implicit object

or an attribute

${firstThing.secondThing}

EL Implicit Object Attribute

pageScoperequestScopesessionScopeapplicationScope

paramparamValues

headerheaderValues

cookie

initParam

attribute objects in page scopein request scopein session scopein application scope

H. Paik (CSE, UNSW) COMP9321, 13s2 Week 4 40 / 77

Page 41: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

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

Page 42: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

EL Basics: Accessing Scoped Variables

Scoped Variables (or Attributes): Any name-value pair attributes storedin 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() tostore/retrieve the name-value attribute pairs. EL gives you an easy way toaccess 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

Page 43: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

EL Basics: Accessing Scoped Variables

Note that you do not have to specify the scope of the variable in theexpression.

The attribute name in the expression (${attribute name}) is searchedin all four locations

Search order: PageContext → HttpServletRequest → HttpSession →ServletContext

Choose unique names for the attribute if you don’t want the containerto 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

Page 44: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

EL Basics: Using dot vs. Using [ ] operator

(Headfirst) p.368

${person.name}

java.util.Map a bean

left must be a Map or a bean

right must be a Map key or a bean property

${person.name}

java.util.Map

getName() or setName()

"name", "Evan"

H. Paik (CSE, UNSW) COMP9321, 13s2 Week 4 44 / 77

Page 45: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

EL Basics: Using dot vs. Using [ ] operatorUsing 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 nameI cannot start with a number

I cannot be a Java keyword

I no spaces

H. Paik (CSE, UNSW) COMP9321, 13s2 Week 4 45 / 77

Page 46: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

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, thefollowing two are the same in a bean.

${person.name} or ${person[“name”]}

H. Paik (CSE, UNSW) COMP9321, 13s2 Week 4 46 / 77

Page 47: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

EL Basics: Using dot vs. Using [ ] operator

(Headfirst) p.370${musicList["something"]}

java.util.Map a bean

left can be a Map, a bean, a List or 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"]}

java.util.List an array

"dance", "Gotye"

getSongList()setSongList()

1: "Zero 7", 2: "Chemical Romance"

1: "Zero 7", 2: "Chemical Romance"

H. Paik (CSE, UNSW) COMP9321, 13s2 Week 4 47 / 77

Page 48: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

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 anarray

The value inside[ ] can be a Map key or a bean property, or an indexinto 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 evaluatedI ${musicMap[Ambient]}I → finds an attribute named Ambient. Use the value of that attribute

as the key into the Map, or return nullI 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

Page 49: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

EL Basics: Using dot vs. Using [ ] operatorIn 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

Page 50: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

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

Page 51: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

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

Page 52: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

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

Page 53: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

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

1Not to be confused with JSP implicit objects.H. Paik (CSE, UNSW) COMP9321, 13s2 Week 4 53 / 77

Page 54: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

EL Basics: EL Implicit Objects

cookies:

let you reference incoming cookies.

The return value is the Cookie object. This means yo access thevalue, you have to use value property (ie., getValue() method)

pageScope, requestScope, sessionScope and applicationScope:

These object let you restrict where the system looks for scopedvariable

eg., ${requestScope.name} only looks into HttpServletRequest

pageContext:

object (not a Map) that represents current page

This object has request, response, session, and servletContextproperties

eg., ${pageContext.session.id}

H. Paik (CSE, UNSW) COMP9321, 13s2 Week 4 54 / 77

Page 55: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

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

Page 56: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

EL Basics: EL Operators

Category OperatorsArithmetic +, -, *, / (or div), % (or mod)

Relational == (or eq), != (or ne), <(or lt), > (or gt),<= (or le), >= (or ge)

Logical && (or and), || (or or), ! (or not)

Validation empty

${item.price * (1 + taxRate[user.address.zipcode])}

H. Paik (CSE, UNSW) COMP9321, 13s2 Week 4 56 / 77

Page 57: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

JSP Standard Tag Library (JSTL)

With JSP actions and EL, you could remove bulk of scriptingelements 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 itdoesn’t exist, you want to call another JSP that will ask for userNamefrom 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

Page 58: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

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

Page 59: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

JSP Standard Tag Library (JSTL)

JSP provides a set of tag library for performing tasks that arecommon in programming

With JSTL and EL, you can do just about everything without usingJSP 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

Page 60: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

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

Page 61: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

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.xmlfile already has instructions which copy the two JAR files to theWEB-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

Page 62: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

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

Page 63: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

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., movieListattribute) and print each element.

H. Paik (CSE, UNSW) COMP9321, 13s2 Week 4 63 / 77

Page 64: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

JSTL Basics: Looping collections

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

Thing to loop over (Array, Collection, Map)

The variable that holds each element

in the collection. It's value changes with each iteration

(HeadFirst) p.438

H. Paik (CSE, UNSW) COMP9321, 13s2 Week 4 64 / 77

Page 65: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

JSTL Basics: Conditional output

Assuming that attributes commentList and memberType are setpreviously ...

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

Page 66: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

JSTL Basics: Conditional output

There is no ELSE construct in JSTL. To check for multiple tests, you willuse: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>

2http:

//www-128.ibm.com/developerworks/java/library/j-jstl0318/H. Paik (CSE, UNSW) COMP9321, 13s2 Week 4 66 / 77

Page 67: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

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

H. Paik (CSE, UNSW) COMP9321, 13s2 Week 4 67 / 77

Page 68: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

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

The attribute Fido does not exist, it will be created (only if value isnot null).

Take,<c:set target="${person}" property="name" value="Evan" />

The target must an expression which evaluates to the Object (not theString ’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 throwsan exception

H. Paik (CSE, UNSW) COMP9321, 13s2 Week 4 68 / 77

Page 69: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

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

Page 70: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

Other things available in JSTL

Core Formatting tools XML tools<c:out> <fmt:formatNumber> <x:parse>

<c:catch> <fmt:parseDate> <x:forEach>

<c:redirect> <fmt:setTimeZone> <x:transform>

<c:import> <fmt:parseNumber> <x:param>

<c:remove> <fmt:setLocale> <x:if>

<c:out> <fmt:message> <x:out>

... ... ...

Easy to learn ... lots of resources online ... some of them in theMessageBoard.

H. Paik (CSE, UNSW) COMP9321, 13s2 Week 4 70 / 77

Page 71: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

JSP Custom Tags

Tags are understood by a program that ’reads’ them; ie., the programknows 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 Javacode that implements the behaviour.

H. Paik (CSE, UNSW) COMP9321, 13s2 Week 4 71 / 77

Page 72: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

JSP Custom Tags

In JSP

<html><body><greet:hello form="brief"/>

doStartTag() { if (form.equals="brief") out.print("Hi ...");return SKIP_BODY;....

Java Code for <greet:hello/>

In Browser (after running the JSP)

Hi ...

</body></html>

<html><body>

</body></html>

H. Paik (CSE, UNSW) COMP9321, 13s2 Week 4 72 / 77

Page 73: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

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

Page 74: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

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

Page 75: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

JSP Custom TagsActions associated with the tags are implemented: HelloTag.java

package hello;

import java.io.IOException;

import javax.servlet.jsp.PageContext;

import javax.servlet.jsp.JspException;

import javax.servlet.jsp.JspTagException;

import 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

Page 76: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

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

Page 77: COMP9321 Web Applications Engineering Java Server Pages …cs9321/14s1/lectures/jsp.pdfCOMP9321 Web Applications Engineering Java Server Pages (JSP). Service Oriented Computing Group,

AdvisorTagHandler classvoid doTag() { // tag implementation}

void setUser(String user) { this.user = user;}

JSP that uses the tag

<html><body>

<% taglib prefix="mine" uri="randomThings" %>

Advisor Page<br>

<mine:advice user="${userName}/>

</body></html>

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

TLD file

(Headfirst) p.473

H. Paik (CSE, UNSW) COMP9321, 13s2 Week 4 77 / 77