the presentation tier of the java ee architecture - uc3m · the presentation tier of the java ee...

69
1 1 Communication Software 2009-2010 © The Authors The Presentation Tier of the Java EE Architecture Authors: Simon Pickin Natividad Martínez Madrid Florina Almenárez Mendoza Address: Departamento de Ingeniería Telemática Universidad Carlos III de Madrid Spain Version: 1.0 Acknowledgements: Marty Hall 2 Communication Software 2009-2010 © The Authors Contents 1. Java Servlets 2. Java Server Pages (JSPs) 3. Integration of servlets and JSPs Bibliography: Core Servlets and JavaServer Pages, vol 1, 2nd edition. Marty Hall and Larry Brown. Prentice Hall 2003 Core Servlets and JavaServer Pages, vol 2, 2nd edition. Marty Hall, Larry Brown, Yaakov Chaikin. Prentice Hall 2007 Java for the Web with Servlets, JSP, and EJB. Budi Kurniawan. New Riders 2002. Part I, chapters 1-5, 8-11, 17

Upload: vandung

Post on 21-Jun-2018

236 views

Category:

Documents


0 download

TRANSCRIPT

1

1

CommunicationSoftware

2009-2010

© The Authors

The Presentation Tierof the Java EE Architecture

Authors: Simon PickinNatividad Martínez MadridFlorina Almenárez Mendoza

Address: Departamento de Ingeniería TelemáticaUniversidad Carlos III de MadridSpain

Version: 1.0

Acknowledgements: Marty Hall

2

CommunicationSoftware

2009-2010

© The Authors

Contents

1. Java Servlets

2. Java Server Pages (JSPs)

3. Integration of servlets and JSPs

Bibliography:• Core Servlets and JavaServer Pages, vol 1, 2nd editi on .

Marty Hall and Larry Brown. Prentice Hall 2003

• Core Servlets and JavaServer Pages, vol 2, 2nd edition . Marty Hall, Larry Brown, Yaakov Chaikin. Prentice Hall 2007

• Java for the Web with Servlets, JSP, and EJB . Budi Kurniawan. New Riders 2002. Part I, chapters 1-5, 8-11, 17

2

3

CommunicationSoftware

2009-2010

© The Authors

Presentation+

Business logic

Web application architectureServlets/JSPs

ClientClientServlets

JSP pagesServlets

JSP pages

Web Container

Application conforming to a “three-tier” architecture(small-scale application with no business tier)

4

CommunicationSoftware

2009-2010

© The Authors

Presentation tier:Java Servlets

3

5

CommunicationSoftware

2009-2010

© The Authors

Contents: Java Servlets

• Generalities– introduction

– advantages– servlet life-cycle

• Servlet API– interfaces, classes and methods– HTTP servlets

– forwarding / including

– session tracking / session management

6

CommunicationSoftware

2009-2010

© The Authors

Introduction to Servlets (1/2)

• A servlet is a Java class used to extend the capabilities of the servers that host applications accessed via a client-server programming model– normally used to extend the capabilities of web servers

• Comparable to a CGI (Common Gateway Interface) program– but with a different architecture

• Managed by a servlet container or engine– JVM + implementation of the servlet API

4

7

CommunicationSoftware

2009-2010

© The Authors

Introduction to Servlets (2/2)

• Interfaces and classes– Packages javax.servletjavax.servlet y javax.servlet.httpjavax.servlet.http

• All servlets must implement the ServletServlet interface, which defines the life-cycle methods, or extend one of the classes:

– GenericServlet : handles generic services.

– HttpServlet : handles HTTP services– extends GenericServlet

ServletServlet

Client

Web browser

Server

Container(JRE)

Servlet

request

response

Source: Web Component Development Wth Servlet and JSP TechnologiesSun Microsystems (course SL-314-EE5)

8

CommunicationSoftware

2009-2010

© The Authors

Advantages of using servlets (1/2)

• Efficiency– one thread per request but single instance of each servlet

• time economy: no process creation delay on each request• space economy: lower memory usage• scalability

– servlet maintains its state between requests• database connections, network connections, etc.

– requests handled via method execution

• Utilities for performing typical server tasks– logging, error management, session management etc.

• Communication– standardised way of communicating with the server

– servlets can share data• enables database connection pooling etc.

5

9

CommunicationSoftware

2009-2010

© The Authors

Advantages of using servlets (2/2)

• Advantages of Java– large number of APIs: JDBC, threads, RMI, networks, etc.

– portability between platforms and servers

– security• virtual machine, type-checking, memory management,

exception handling, etc. • security manager

– object-oriented

– large community of developers

– external code easily used

10

CommunicationSoftware

2009-2010

© The Authors

Servlet Life-Cycle

• Instantiation & initialisation (on first request):– if no instance of servlet exists, the web container:

• loads the servlet class• creates an instance • initialises the instance by calling the servlet’s init method

• Handling of subsequent requests– container creates new thread that calls the service

method of the instance– the service method determines what type of request has

arrived and calls the appropriate method.

• Destruction– when the container decides to remove a servlet, it first calls

its destroy method

6

11

CommunicationSoftware

2009-2010

© The Authors

Servlet Lifecycle Consequences (1/2)

• Single virtual machine:– data sharing between servlets

• Persistence (in memory) of instances– reduced memory consumption

– elimination of instantiation and initialisation time

– persistence (in memory) of state, data and resources• persistent attributes of the servlet• permanent database connections, etc

– persistence (in memory) of threads

12

CommunicationSoftware

2009-2010

© The Authors

Servlet Lifecycle Consequences (2/2)

• Concurrent requests– need for synchronisation to manage concurrent access

• class or instance attributes, databases, etc.

– if servlet implements SingleThreadModel interface• no concurrent access to instance attributes

(may be concurrent access to class attributes) • can lead to significantly-reduced performance• deprecated since version 2.4

7

13

CommunicationSoftware

2009-2010

© The Authors

Contents: Java Servlets

• Generalities– introduction

– advantages– servlet tasks

– life-cycle

• API de Servlets– interfaces, classes y methods

– HTTP servlets

– forwarding / including

– session tracking / session management

14

CommunicationSoftware

2009-2010

© The Authors

Servlet API

• Packages– javax.servlet

• 6 interfaces– Servlet

– ServletConfig

– ServletContext

– ServletRequest

– ServletResponse

– RequestDispatcher

• 3 classes– GenericServlet

– ServletInputStream

– ServletOutputStream

• 2 exception classes– ServletException

– UnavailableException

8

15

CommunicationSoftware

2009-2010

© The Authors

Servlet Interface Methods (1/2)

• void init(ServletConfig config)

– called exactly once after servlet is instantiated

– servlet can be instantiated (depending on how registered) • either when the first user accesses the servlet URL• or when the web server is started

– without arguments: server-independent initialisation• variable initialisation, connection to databases etc.

– with arguments: server-dependent initialisation• info obtained from deployment descriptor web.xml (from servlet 2.3)

and placed in ServletConfig object• configuration of databases and password files, setting of server-

efficiency parameters, etc.

• void service(ServletRequest req,ServletResponse res)

– invoked by container to enable servlet to respond to request

16

CommunicationSoftware

2009-2010

© The Authors

Servlet Interface Methods (2/2)

• void destroy()

– container may decide to remove a previously-loaded servlet instance, e.g.

• system administrator decision• timeout: idle for too long

– before doing so, calls the destroy method to cleanup• close database connections• stop threads• write cookie lists or hit counts to disk• …

– if Web server crashes, destroy method not called!• conclusion: maintain state in a proactive manner

(“housekeeping” at regular intervals)

9

17

CommunicationSoftware

2009-2010

© The Authors

ServletConfig Interface (1/3)

• Configuration object used by servlet container to pass information to the servlet during its initialisation– config info obtained from the deployment descriptor web.xml

– for each servlet registered, a set of initial parameters (name-value) can be specified,e.g.

<web-app>

<servlet><servlet-name>ConfigExample</servlet-name>

<servlet-class>ConfigExampleServlet</servlet-class>

<init-param><param-name>adminEmail</param-name>

<param-value>[email protected]</param-value></init-param>

<init-param> . . . </init-param></servlet>

. . .</web-app>

18

CommunicationSoftware

2009-2010

© The Authors

ServletConfig Interface (2/3)

public void init(ServletConfig config) throws Servl etException

{

Enumeration parameters = config.getInitParameterNam es();

while (parameters.hasMoreElements()) {

String parameter = (String) parameters.nextElement( );

System.out.println("Parameter name : " + parameter) ;

System.out.println("Parameter value : " +

config.getInitParameter(parameter));

}

}

public void init(ServletConfig config) throws Servl etException

{

Enumeration parameters = config.getInitParameterNam es();

while (parameters.hasMoreElements()) {

String parameter = (String) parameters.nextElement( );

System.out.println("Parameter name : " + parameter) ;

System.out.println("Parameter value : " +

config.getInitParameter(parameter));

}

}

• Example: overwrite the init method in order to print the information contained in the ServletConfigobject

10

19

CommunicationSoftware

2009-2010

© The Authors

ServletConfig Interface (3/3)

• N.B. if the init method (with parameters) of the Servletinterface (implemented in the GenericServlet class) is redefined, the ServletConfig object will not be saved and will not then be available after initialisation.

• Solution: either call Servlet.init (super.init if extending the GenericServlet or HttpServlet class) from inside the redefined init or explicitly save it, e.g.

ServletConfig servlet_config;public void init(ServletConfig config) throws

ServletException {servlet_config = config;

}

The advantage of the former solution is that in this case the ServletConfig object will still be obtainable via the getServletConfig method whereas with the second solution it will not.

20

CommunicationSoftware

2009-2010

© The Authors

ServletContext Interface

• Defines a set of methods used by the servlet to communicate:– with its container (to obtain MIME type of a file, a dispatcher etc.)

– with other servlets

• A context is defined– per Web application– per virtual machine

• Web application

– collection of servlets and contents installed in a specific subset (subdirectory) of the server namespace

• The information about the Web application of which a servlet forms a part is stored in the ServletConfig object

11

21

CommunicationSoftware

2009-2010

© The Authors

ServletContext Attributes

• The context is obtained from the configurationServletContext sc =

Servlet.getServletConfig().getServletContext();

• Objects can be stored as attributes, identified by namesc.setAttribute( “ myObject ” , anObject);

If the name exists, the context is updated with the content of the new object

• Any servlet in the same context can recover the object that has been stored

MyClass mc = (MyClass)sc.getAttribute( “ myObject ” );

• The names of all the stored attributes can be obtainedEnumeration att = sc.getAttributeNames();

22

CommunicationSoftware

2009-2010

© The Authors

ServletRequest and ServletResponse Interfaces

• Objects created by the container and passed as arguments to the methods handling the request

• ServletRequest encapsulates request information

– includes parameters, attributes and an input stream

– methods: getParamaterNames() , getParameter() , getAttributeNames() , getRemoteAddr() , getRemoteHost() , getProtocol() , getContentType() , …

• ServletResponse encapsulates response info– methods: getWriter() , reset() , getBufferSize() ,

getLocale() , getOutputStream() , isCommitted() , …

12

23

CommunicationSoftware

2009-2010

© The Authors

HTTP Servlets ( javax.servlet.http )

• Inherits from javax.servlet.HttpServlet

• The HttpServlet.service() method invokes the doXXXmethod according to the HTTP-method of incoming request

void doGet (HttpServletRequest req,HttpServletResponse res)

void doPost(HttpServletRequest req,HttpServletResponse res)

void do....(HttpServletRequest req,HttpServletResponse res)

• Overriding service() method not recommended

• Main work of the servlet usually done in doXXX method:– example: to process GET requests redefine doGet

24

CommunicationSoftware

2009-2010

© The Authors

The doGet , doPost , doXXX Methods

• 99% of servlets override doGet or doPost method

• Also: doDelete , doPut , doOptions , doTrace

• No doHead method– the service method simply calls doGet but omits the

body, returning only headers and status code

• In general, not necessary to define doOptions– supported automatically by the service method (along with

HEAD& TRACE)

– if doGet method exists, the service method answers OPTIONSrequests by returning an Allow header, indicating that GET, HEAD, OPTIONSy TRACEare supported

13

25

CommunicationSoftware

2009-2010

© The Authors

HttpServlet

service()

request

response

doGet() doGet()

doPost() doPost()

Implemented by the subclass

Implemented byHttpServlet

class Hello extends HttpServlet

GET

POST

26

CommunicationSoftware

2009-2010

© The Authors

HTTP Servlet Tasks (1/2)

1. Read data sent by the user• typically sent via a web page form

• may also originate in an applet or HTTP client app.

2. Retrieve user information in HTTP request headers• browser capabilities

• cookies

• details of the client host etc.

3. Generate results• directly calculating the response

• calling another (possibly remote) server (possibly accessed via RMI or CORBA)

• accessing a database, etc.

14

27

CommunicationSoftware

2009-2010

© The Authors

HTTP Servlet Tasks (2/2)

4. Format the results• normally inside an HTML web page

5. Set the required HTTP response headers• type of document returned (e.g. HTML)

• cookies

• cache parameters, etc

6. Return the document to the client• in the form of a text document (e.g. HTML)

• binary format (e.g. GIF)

• compressed (e.g. gzip)…

28

CommunicationSoftware

2009-2010

© The Authors

Basic HTTP Servlet Template

import java.io.*;

import javax.servlet.*;import javax.servlet.http.*;

public class ServletTemplate extends HttpServlet {

// Use "request" to read incoming HTTP headers (e.g. c ookies)// and HTML form data (e.g. data user entered and subm itted).

// Use "response" to specify the HTTP response status code// and headers (e.g. the content type, cookies).

public void doGet(HttpServletRequest request ,HttpServletResponse response )

throws ServletException, IOException {

// Use "out" to send content to browser.PrintWriter out = response.getWriter();

}}

15

29

CommunicationSoftware

2009-2010

© The Authors

Example 1: Text Generation (1/2)

import java.io.*;

import javax.servlet.*;import javax.servlet.http.*;

public class HelloWorld extends HttpServlet {

public void doGet(HttpServletRequest request,HttpServletResponse response)

throws ServletException, IOException {PrintWriter out = response.getWriter();

out.println("Hello World");}

}

30

CommunicationSoftware

2009-2010

© The Authors

Example 1: Text Generation (2/2)

16

31

CommunicationSoftware

2009-2010

© The Authors

Example 2: HTML Generation (1/2)

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class HelloWWW extends HttpServlet {

public void doGet(HttpServletRequest request,HttpServletResponse response)

throws ServletException, IOExceptio {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

String docType =

"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Tran sitional//EN\" "

+ "\"http://www.w3.org/TR/1999/REC-html401-19991224 /loose.dtd\" >\n";

out.println(docType +

"<html>\n" +

"<head><title>Hello WWW</title></head>\n" +

"<body>\n" +

"<h1>Hello WWW</h1>\n" +

"</body></html>");

}

}

32

CommunicationSoftware

2009-2010

© The Authors

Example 2: HTML Generation (2/2)

17

33

CommunicationSoftware

2009-2010

© The Authors

HTTPServletRequest interfaceReading HTML Form Data from Servlets

http://host/path?user=Marty+Hall&origin=bwi&dest=la x

form data / query data (GET)

public String getParameter(String name)

• method of HttpServletRequest inherited from ServletRequest

• applies in case of data sent by GET or by POST (server knows which)

• name: name of parameter whose value is required (case sensitive)

• return value: – url-decoded value of first occurrence of parameter name

– empty string if parameter exists but has no value– null if parameter does not exist

• for parameters that potentially have several values:– getParameterValues (returns an array of Strings)

• to obtain a complete list of parameters (debugging):– getParameterNames (returns an enumeration whose elements

can be cast to Strings and used ingetParameter calls)

34

CommunicationSoftware

2009-2010

© The Authors

http://host/path?user=Marty+Hall&origin=bwi&dest=la x

form data / query data (GET)

CGI:• Different methods for GETand POST

• Parse the “query string” to extract names and values:1. read data from QUERY_STRING environment variable (GET) or

standard input (POST)

2. chop pairs at “&” (parameter separator) then separate parameter names (l.h.s of “=”) from values (r.h.s. of “=”)

3. URL-decode the parameter values

• Take into account that there may be parameters– whose values are omitted– for which multiple values are sent (separately)

Reading Form Data from a CGI Progam(for Comparison Purposes)

18

35

CommunicationSoftware

2009-2010

© The Authors

Example 3: Reading three explicit parameters

package coreservlets // source: “Core Servlets…”, Marty Hall et al

import java.io.*;import javax.servlet.*;import javax.servlet.http.*;

public class ThreeParams extends HttpServlet {public void doGet(HttpServletRequest req, HttpServl etResponse res)

throws ServletException, IOException {res.setContenttype("text/html");PrintWriter out = res.getWriter();String title = "Reading Three Request Parameters";out.println(ServletUtilities.headWithTitle(title) +

"<body bgcolor=\"#FDF5E6\">\n" +"<h1 align="center">" + title + "</h1>\n <ul>\n" +" <li><b>param1</b>: " +req.getParameter("param1") + "</li>\n" +" <li><b>param2</b>: " +req.getParameter("param2") + "</li>\n" +" <li><b>param3</b>: " +req.getParameter("param3") + "</li>\n" +"</ul>\n</body></html>");

}}

36

CommunicationSoftware

2009-2010

© The Authors

Example 3: ServletUtilities Class

public class ServletUtilities {

public static final String DOCtype =

"<!DOCtype HTML PUBLIC \"-//W3C//DTD HTML 4.01 Tran sitional//EN\"" +

" \"http://www.w3.org/TR/1999/REC-html401-19991224/ loose.dtd\">";

public static String headWithTitle (String title)

return(DOCtype + "\n" + "<html>\ n" + "<head><title>" + title +

"</title></head>\n");

}

}

19

37

CommunicationSoftware

2009-2010

© The Authors

Example 3: HTML Form

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transi tional//EN" "http://www.w3.org/TR/1999/REC-html401-19991224/loo se.dtd">

<html><head>

<title>Collecting Three Parameters</title></head><body bgcolor="#FDF5E6">

<h1 align="center">Collecting Three Parameters</h1>

<form action="/servlet/coreservlets.ThreeParams">First Parameter: <input type="text" name="param1" ><br />Second Parameter: <input type="text" name="param2" ><br />Third Parameter: <input type="text" name="param3" ><br /><center><input type="submit" value="Enviar consulta "></center>

</form>

</body></html>

38

CommunicationSoftware

2009-2010

© The Authors

Example 3: HTML Form Appearance

20

39

CommunicationSoftware

2009-2010

© The Authors

Example 3: Servlet Response

40

CommunicationSoftware

2009-2010

© The Authors

Example 4: Reading All Parameters (1/3)

package coreservlets // source: “Core Servlets…”, Marty Hall et al

import java.io.*;import javax.servlet.*;import javax.servlet.http.*;import java.util.*;

public class ShowParameters extends HttpServlet {

public void doGet(HttpServletRequest req, HttpServl etResponse res)

throws ServletException, IOException {res.setContenttype("text/html");PrintWriter out = res.getWriter();String title = "Reading All Request Parameters";out.println(ServletUtilities.headWithTitle(title) +

"<body bgcolor=\"#FDF5E6\">\n" +"<h1 align="center">" + title + "</h1>\n" +"<table border="1" align="center">\n" +"<tr bgcolor=\"#FFAD00\">\n" +"<th>Parameter name</th><th>Parameter value(s)</th> </tr>");

Enumeration paramnames = req.getParameternames();

21

41

CommunicationSoftware

2009-2010

© The Authors

Example 4: Reading All Parameters (2/3)

while (paramnames.hasMoreElements()) {String paramname = (String)paramnames.nextElement() ;out.print("<tr><td>" + paramname + "</td>\n<td>");String[] paramvalues = req.getParametervalues(param name);

if (paramvalues.length == 1) {String paramvalue = paramvalues[0];if (paramvalue.length() == 0)

out.println("<i>No value</i>");else

out.println(paramvalue);} else {

out.println("<ul>");for(int i=0; i<paramvalues.length; i++)

out.println("<li>" + paramvalues[i] + "</li>");out.println("</ul>");

} // ifout.println("</td></tr>");

} // while

out.println("</table>\n</body></html>");

}

42

CommunicationSoftware

2009-2010

© The Authors

Example 4: Reading All Parameters (3/3)

// Since servlet is for debugging, handle GET and POST identically.public void doPost(HttpServletRequest req, HttpServ letResponse res)

throws ServletException, IOException {

doGet(req, res);

}

}

22

43

CommunicationSoftware

2009-2010

© The Authors

Example 4: HTML Form

<form action="/servlet/coreservlets.ShowParameters" method="POST">

Item Number: <input type="text" name="itemNum"><br />Quantity: <input type="text" name="quantity"><br />Price Each: <input type="text" name="price" value=" $"><br /><hr />First name: <input type="text" name="firstname"><br />Last name: <input type="text" name="lastname"><br / >Credit Card:<br />

&nbsp;&nbsp;<input type="radio" name="cardType"value="Visa">Visa<br />

&nbsp;&nbsp;<input type="radio" name="cardType"value="Master Card">Master Card<br />

&nbsp;&nbsp;<input type="radio" name="cardType"value="Amex">American Express<br />

Credit Card Number: <input type="password" name="ca rdNum"><br />Repeat Credit Card Number:

<input type="password" name="cardNum"><br />

<center><input type="SUBMIT" value="Submit Order">< /center>

</form>

44

CommunicationSoftware

2009-2010

© The Authors

Example 4: HTML Form Appearance

23

45

CommunicationSoftware

2009-2010

© The Authors

Example 4: Servlet Response

46

CommunicationSoftware

2009-2010

© The Authors

HTTPServletRequest interfaceHandling Request Headers (1/2)

• String getHeader(String name)

– accepts header name as string (not case sensitive)

– returns header as string, or null if no header was found

• Cookie[] getCookies()

– returns contents of Cookie header as array of Cookie objects

• String getAuthType() y String getRemoteUser()

– return the elements of the Authorization header

• int getContentLength()

– returns value of ContentLength header or -1 if length unknown(length, in bytes, of request body for POST requests)

• String getContentType()

– returns the value of the Content-Type header

24

47

CommunicationSoftware

2009-2010

© The Authors

HTTPServletRequest interfaceHandling Request Headers (2/2)

• long getDateHeader(String name)int getIntHeader(String name)

– returns the value of the specified header as a long or an int

– former returns value in milliseconds from Jan 1st 1970

• Enumeration getHeaderNames()

– returns enumeration with names of all request headers received

• Enumeration getHeaders(String name)

– returns enumeration with all values of all occurrences of the specified header (e.g. Accept-Language can appear several times)

48

CommunicationSoftware

2009-2010

© The Authors

HTTPServletRequest interfaceHandling the First Line of the Request

• String getMethod()

– returns the method of the request (GET, POST, etc.)

• String getRequestURI()

– returns path, i.e. part of the URI of the request between host:portand query string (recall: scheme://host:port/path?query_string)

e.g. returns /a/b.html for HTTP request commencing as follows:

GET /a/b.html?name=simon HTTP/1.1Host: www.it.uc3m.es

• String getProtocol()

– returns the name and version of the protocol in the form: protocol/majorVersion.minorVersion

– example: “HTTP/1.1”

25

49

CommunicationSoftware

2009-2010

© The Authors

Example 5: Showing Request Headers (1/2)

// source: “Core Servlets…”, Marty Hall et al

public class ShowHeadersServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletExceptio n, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("Request Method: " + request.getMethod() + "<br/>");

out.println("Request URI: " + request.getRequestURI() + "<br/>");

out.println("Protocol: " + request.getProtocol() + "<br/>");

out.println("<hr /><br />");

Enumeration enumeration = request.getHeaderNames();

while (enumeration.hasMoreElements()) {

String header = (String) enumeration.nextElement();

out.println(header + ": " + request.getHeader(header) + "<br/>");

}

}

50

CommunicationSoftware

2009-2010

© The Authors

Example 5: Servlet Response

26

51

CommunicationSoftware

2009-2010

© The Authors

HTTPServletResponse InterfaceSetting Response HTTP Status Codes

• void setStatus(int sc)

– important:• status code and headers can be set in any order (servlet orders them) • but must always be set before using the PrintWriter .• from version 2.2, some output buffering is permitted

(headers and status codes can be modified until buffer full)

– accepts one of the constants defined as status codes

• void sendError(int status-code, String msg)

void sendError(int status-code)

– sends a status code along with a short message that will be formatted inside HTML document and sent to client

• void sendRedirect(String location)

– sends temporary redirect to client with new URL as parameter.• from version 2.2, URL may be relative to servlet root (begins with “/”) or

current directory: conversion to full URL performed by web container.

– generates both status code and header

52

CommunicationSoftware

2009-2010

© The Authors

HTTPServletResponse InterfaceSetting Response Headers

• void setHeader(String name, String value)

– sets header with identifier “name” to the value “value ”

• void setDateHeader(String name, long date)

– value in milliseconds since 1970 (System.currentTimeMillis )

– sets header “name” to value as GMT time string

• void setIntHeader(String name, int value)

– accepts value as integer– sets header “name” to value as string

• From version 2.2– above methods re-set headers if called more than once.

– to add a header more than once use:• addHeader• addDateHeader

• addIntHeader

27

53

CommunicationSoftware

2009-2010

© The Authors

HTTPServletResponse InterfaceSetting Some Common Response Headers

• void setContentType(String type)

– generates the Content-Type header (MIME type of the contents).

– used by nearly all servlets

• void setContentLength(int len)

– generates the Content-Length header

• void addCookie(Cookie cookie)

– inserts a cookie in the Set-Cookie header

• void sendRedirect(String location)

– mentioned previously

54

CommunicationSoftware

2009-2010

© The Authors

Example 6a: Authentication (1/3)

public class LoginServlet extends HttpServlet {

private void sendLoginForm(HttpServletResponse resp onse,

boolean withErrorMessage )

throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<html>");

out.println("<head><title>Login</title></head>");

out.println("<body>");

if ( withErrorMessage )

out.println("Login failed. Please try again.<br />" );

out.println("<br />");

out.println("<br/>Please enter your user name and p assword.");

28

55

CommunicationSoftware

2009-2010

© The Authors

Example 6a: Authentication (2/3)

out.println("<br /><form action=\"\" method=\"POST\ ">");

out.println("<br />User Name: <input type=\"text\"

name=\"userName\">");

out.println("<br />Password: <input type=\"password \"

name=\"password\">");

out.println("<br /><input type=\"submit\"

name=\"Submit\">");

out.println("</form>");

out.println("</body>");

out.println("</html>");

}

public void doGet(HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException {

sendLoginForm(response, false );

}

56

CommunicationSoftware

2009-2010

© The Authors

Example 6a: Authentication (3/3)

public void doPost(HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException {

String userName = request.getParameter("userName");

String password = request.getParameter("password");

if (userName!=null && password!=null &&

userName.equals("swc") && password.equals("it")) {

response.sendRedirect("http://domain/WelcomePage");

} else {

sendLoginForm(response, true );

}

}

} response.sendError(response.SC_FORBIDDEN, "Login Failed ");response.sendError(response.SC_FORBIDDEN, "Login Failed ");

29

57

CommunicationSoftware

2009-2010

© The Authors

Example 6a: Servlet Response on Failure

sendError

58

CommunicationSoftware

2009-2010

© The Authors

Example 6a: Servlet Response on Success

String userName = request.getParameter("userName");. . .out.println("<p>Your user name is: " + userName + " </p>") ;

• The request object is not the same one after redirection

30

59

CommunicationSoftware

2009-2010

© The Authors

Forwarding / Including Requests

Use a RequestDispatcher

• Obtained by calling method getRequestDispatcher of– ServletContext

• supplying URL relative to the server root as argument

– ServletRequest• supplying URL relative to the HTTP request as argument

• Pass control to resource located at URL: forward

– arguments: request and response objects

– origin servlet cannot set output body

– origin servlet can set response headers but not commit them– changes path to be relative to target not origin

• Include output generated by resource located at URL: include

– arguments: request and response objects

– target resource cannot modify response headers

60

CommunicationSoftware

2009-2010

© The Authors

Example 6b: Authentication (3/3)

public void doPost(HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException {

String userName = request.getParameter("userName");

String password = request.getParameter("password");

if (userName!=null && password!=null &&

userName.equals("swc") && password.equals("it")) {

response.sendRedirect("http://domain/WelcomePage");

} else {

sendLoginForm(response, true);

}

}

RequestDispatcher rd = request.getRequestDispatcher ( "WelcomePage");

rd.forward(request, response);

RequestDispatcher rd = request.getRequestDispatcher ( "WelcomePage");

rd.forward(request, response);

31

61

CommunicationSoftware

2009-2010

© The Authors

Example 6b: Servlet Response on Success

String userName = request.getParameter("userName");. . .out.println("<p>Your user name is: " + userName + " </p>");

• The request object is the same one after forwarding

62

CommunicationSoftware

2009-2010

© The Authors

Cookies

• HTTP is a stateless protocol

• Cookies are small pieces of information– sent from server to client in an HTTP response

– returned from client to server in subsequent HTTP requests

• A cookie is therefore a means for the server to store information on the client

• A cookie has– a name and an identifier

– optionally, attributes such as path, comment, domain, maximum lifespan, version number

32

63

CommunicationSoftware

2009-2010

© The Authors

Use of Cookies

• State of an e-commerce session (session tracking) – example: shopping cart

• Registering without login and password– only for low-security sites

– site can remember user data

• Customising a site– site can remember user interests

• Focusing advertising– site can focus advertising in function of user activity profile

64

CommunicationSoftware

2009-2010

© The Authors

Problems with Cookies

• Not so much a security problem– not executable or interpretable– size and number (per site and total) is limited (4KB, 20, 300)

• Privacy problem– servers can remember your previous actions

– cookies can be shared between servers• e.g. both loading an image with associated cookie from third

site; such images may even be received in an HTML e-mail!

– secret information (credit card no. etc.) should not be stored in a cookie but on the server

• cookie only stores user ID; as a user, how can we be sure?

• Many users deactivate cookies– servlets can use cookies but are not dependent on them

33

65

CommunicationSoftware

2009-2010

© The Authors

Creating and Populating Cookies in Servlets

Methods of the Cookie class

• Cookie(String name, String value)

– constructor receives the name and value of the cookie

– forbidden characters: [ ] ( ) = , “ / ? @ : ;

• getXxx() y setXxx()

– where Xxx is the name of the attribute

– attributes:• type String : Comment, Domain , Name, Path , Value

• type int : MaxAge, Version• type boolean : Secure

66

CommunicationSoftware

2009-2010

© The Authors

Reading and Writing Cookies in Servlets

• To read cookies from the request object

Cookie[] HttpServletRequest.getCookies()

• To write cookies to the response object

void HttpServletResponse.addCookie(Cookie cookie)

• To reuse a cookie from the request:– must still use addCookie (just using setValue is not enough)

– must reset all attributes (values not transmitted in the request)

• See also method getCookieValue

34

67

CommunicationSoftware

2009-2010

© The Authors

Session Tracking

• Client at on-line shop adds item to their shopping cart:– how does server know what’s already in the cart

• Client at on-line shop proceeds to check-out– how does server know which shopping cart is theirs?

• Implementing session tracking with cookies– complicated: generate unique session ID, associate sessionID and

session info in hash table, set cookie expiration time,…

• Implementing session tracking with URL-rewriting– must encode all URLs that refer to you own site

– all pages must be dynamically generated

• Implementing session tracking with hidden form fields– tedious

– all pages must be the result of form submissions

68

CommunicationSoftware

2009-2010

© The Authors

Interfaz HttpSession : Session Object

• Creates a session between the HTTP client and the HTTP server that persists through different requests.

• Allows servlets to:– see and manipulate session information such as session identifier,

session creation time, last access time,…– link session objects, allowing user information to persist through

different connections

• To obtain the session associated to a request– use getSession() or getSession(boolean create) of

HttpServletRequest

– if there is no session already associated to the request• getSession() / getSession(true) creates a new one• getSession(false) returns null

35

69

CommunicationSoftware

2009-2010

© The Authors

Storing Information in Session Object

• Arbitrary objects can be stored inside a session– uses hashtable-like mechanism– store and retrieve with setAttribute and getAttribute

• To support– distributed Web applications

– persistent sessions

session data must implement java.io.Serializable

70

CommunicationSoftware

2009-2010

© The Authors

Session Tracking: HttpSession (1/2)

• Associating information with a session– void setAttribute(String name, Object value)

– void setMaxInactiveInterval(int interval)

– void removeAttribute(String name)

• Terminating completed or abandoned sessions– automatically, after MaxInactiveInterval time has

elapsed– via the method void invalidate()

36

71

CommunicationSoftware

2009-2010

© The Authors

Session Tracking: HttpSession (2/2)

• Looking up information associated with a session– Object getAttribute(String name)

– Enumeration getAttributeNames()

– String getId()

– long getCreationTime()

– long getLastAccessedTime()

– ServletContext getServletContext()

– int getMaxInactiveInterval()

– boolean isNew()

72

CommunicationSoftware

2009-2010

© The Authors

Session Tracking With Cookies Disabled

• Servlet session tracking mechanism uses– cookies, if they are enabled,

– URL-rewriting, otherwise

• To ensure URL-rewriting works: encode URLs– server uses cookies: no effect

– server uses URL-rewriting: session ID appended to URLhttp://host/path/file.html?jsession=1234

• For any hypertext links back to same site in code– use response.encodeURL

• For any use of sendRedirect in code– use response.encodeRedirectURL

37

73

CommunicationSoftware

2009-2010

© The Authors

Executing Servlets

• Suppose this configuration of Tomcat Web server ( in web.xml file):<servlet>

<servlet-name>FirstServlet</servlet-name>

<description>My first HTTP Servlet</description>

<servlet-class>FirstServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>FirstServlet</servlet-name>

<url-pattern>/servlets/myFirstServlet</url-pattern>

</servlet-mapping>

1. Introduce URL of servlet in a browser, e.g.– http://host/app/servlets/myFirstServlet

2. Call it from inside an HTML Web page– link, form action or reloading specified in METAtag, e.g.

<a href= “ servlets/myFirstServlet ” >My first servlet</a>

3. Transfer control from another servlet, e.g.– SendRedirect , RequestDispatcher

74

CommunicationSoftware

2009-2010

© The Authors

Presentation tier:JavaServer Pages

38

75

CommunicationSoftware

2009-2010

© The Authors

Contents: Java Server Pages

• Introduction

• Predefined variables

• JSP Instructions– script– directive

– action

• JavaBeans

• JSP Standard Tag Library (JSTL) – Expression Language (EL)

76

CommunicationSoftware

2009-2010

© The Authors

Introducción

• Response HTML: servlets always generate all the page:– in many cases only small part of HTML page is dynamic

• Solution: JavaServer Pages (JSP)– technology enabling mixture of

• static HTML• dynamic content generated by servlets

• Advantages of JSP:– widely supported by web platforms and servers

– full access for dynamic part to servlet & Java technology (JavaBeans etc.)

• JSPs are compiled to servlets– on first use or on deployment

39

77

CommunicationSoftware

2009-2010

© The Authors

JSP Processing

Web server

Container

http://host/app/hello.jsp

<%

%>

hello.jsp

hello_jsp

hello_jsp.java

hello_jsp.class«create»jspInit

_jspService

jspDestroy

Source: Web Component Development Wth Servlet and JSP Technologies.Sun Microsystems (course SL-314-EE5)

78

CommunicationSoftware

2009-2010

© The Authors

Predefined Variables / Implicit Objects (1/2)

• request– the HttpServletRequest object

• response– the HttpServletResponse object

• session– the HttpSession object associated with the request

• out– the PrintWriter object used to send output to the client

(this is a buffered PrintWriter called a JspWriter )

• page– synonym of this (little used)

40

79

CommunicationSoftware

2009-2010

© The Authors

Predefined Variables / Implicit Objects (2/2)

• exception

– error pages

• application ,– the ServletContext object

– data can be stored in ServletContext using getAttribute y setAttribute

– recall: data stored in ServletContext shared by all servlets (of the same Web application)

• config

– the ServletConfig object for this page

• pageContext

– object of JSP-specific class: PageContext ,

– point of access to page attributes

– corresponds to the context of the servlet instance

80

CommunicationSoftware

2009-2010

© The Authors

JSP Instructions

• Three types of embedded instructions:– script elements

• specify Java code that will become part of servlet

– directives• control overall structure of servlet

– actions• actions that take place when the page is requested • control behaviour of JSP engine

• Comments:– <%-- this is a comment --%>

41

81

CommunicationSoftware

2009-2010

© The Authors

Script Elements

• Expressions: <%= expression %>

– expressions to be evaluated; result included in output– e.g. <%= new java.util.Date() %>

• Scriptlets: <% code %>– blocks of java code inserted into method _jspService

(called by service )

– e.g. <% try{... } catch(){... } %>

• Declarations: <%! code %>

– declarations inserted into servlet class body, outside of existing methods

– e.g. <%! int i=0; %>

82

CommunicationSoftware

2009-2010

© The Authors

Expressions: <%= expression %>

• Java expressions

• Output converted to a string

• Evaluated at run-time, when page requested– access to information about request

• Final semi-colon “; ” not needed

• Examples– <%= java.util.Calendar.getInstance().getTime() %>

– <p>Your session Id: <%= session.getId() %>

– request:http://host/confirmation.jsp?title=core+web

response:Thanks for ordering <%= request.getParameter("title ") %>

42

83

CommunicationSoftware

2009-2010

© The Authors

Example 1: Expressions

// Source: “Core Servlets…”, Marty Hall et al<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transit ional//EN"><html>

<head><title>JSP Expressions</title><meta name="keywords"

content="JSP,expressions,JavaServer Pages,servlets" /><meta name="description"

content="A quick example of JSP expressions" /><link rel="stylesheet" href="JSP-Styles.css" type=" text/css"/>

</head><body>

<h1>JSP Expressions</h1><ul>

<li>Current time: <%= new java.util.Date() %> </li><li>Server: <%= application.getServerInfo() %> </li><li>Session ID: <%= session.getId() %> </li><li>The <code>testParam</code> form parameter:

<%= request.getParameter("testParam") %> </li></ul>

</body></html>

84

CommunicationSoftware

2009-2010

© The Authors

Example 1: Server Response

43

85

CommunicationSoftware

2009-2010

© The Authors

Scriptlets: <% code %>

• Tasks that cannot be carried out using expressions– setting response headers

– writing to the server log

– updating a database

– executing code that contains loops, conditionals, etc

• Examples:– setting response headers

<% response.setContentType(“text/plain”); %>

– conditional code<% if (Math.random() < 0.5) { %>

<p>Have a <b>nice</b> day!</p><% } else { %>

<p>Have a <b>lousy</b> day!</p><% } %>

86

CommunicationSoftware

2009-2010

© The Authors

Example 2: Scriptlets

// Source: “Core Servlets…”, Marty Hall et al<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transit ional//EN"><html>

<head><title>Color Testing</title></head><% String bgColor = request.getParameter("bgColor") ;

if ((bgColor == null) || (bgColor.trim().equals("") )) { bgColor = "WHITE";

} %><body bgcolor="<%= bgColor %>">

<h1 align="center">Testing a Background of "<%= bgC olor %>"</h1>

</body></html>

44

87

CommunicationSoftware

2009-2010

© The Authors

Declarations: <%! declaration %>

• Definition of methods and fields– inserted into servlet outside of existing methods

• Produces no output– usually used in conjunction with expressions and scriptlets

• Examples– <%! String getSystemTime() {

return Calendar.getInstance().getTime.toString();} %>

– <%! private int accessCount = 0; %>

<h2>Accesses to page since server reboot:<%= ++accessCount %></h2>

88

CommunicationSoftware

2009-2010

© The Authors

Example 3: Declarations

// Source: “Core Servlets…”, Marty Hall et al<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transit ional//EN"><html>

<head><title>JSP Declarations</title><link rel="stylesheet" href="JSP-Styles.css" type=" text/css" />

</head><body>

<h1>JSP Declarations</h1><%! private int accessCount = 0; %><h2>Accesses to page since server reboot: <%= ++acc essCount %></h2>

</body></html>

45

89

CommunicationSoftware

2009-2010

© The Authors

Example 3: Some Observations

• Multiple client requests to same servlet:– do not result in the creation of multiple servlet instances

– multiple threads call the service method of same instance• though careful with use of SingleThreadModel

• Therefore:– instance variables are shared by multiple requests– accessCount does not need to be declared as static

90

CommunicationSoftware

2009-2010

© The Authors

Directives: <%@ directive attibutes %>

• Affect global structure of servlet generated from JSP

• Syntax: <%@ directive attribute="value" %><%@ directive attribute1="value1“

...attribute N="value N" %>

• Three types of directives: – page :

allows servlet structure to be controlled through class imports,customising of servlet superclass, setting content type, etc.

– include :allows a file to be included in servlet class at time of translation from JSP to servlet

– taglib :allows custom markup tags to be defined, extending the functionality of JSP

46

91

CommunicationSoftware

2009-2010

© The Authors

Attributes of the page Directive

• import

• contentType

• isThreadSafe

• session

• buffer

• autoflush

• extends

• info

• errorPage

• isErrorPage

• language

92

CommunicationSoftware

2009-2010

© The Authors

page Directive: import Attribute

• Specify the packages imported by the servlet

• By default, the generated servlet will import:– java.lang.*

– javax.servlet.*

– javax.servlet.jsp.*

– javax.servlet.http.*

and possibly others (server specific)

• Example:<%@ page import="java.util.*, java.io.*" %>

47

93

CommunicationSoftware

2009-2010

© The Authors

page Directive: contentType Attribute

• Sets the Content-Type response header

<%@ page contentType=" MIME-Type" %>

<%@ page contentType=" MIME-Type;charset= Character-Set" %>

• Example<%@ page contentType="text/html;

charset=ISO-8859-1" %>

94

CommunicationSoftware

2009-2010

© The Authors

The include Directive

• Use:<%@ include file=“ relative URL” %>

• Adds content of specified file before translating to servlet– included files may contain JSP constructs

• Code re-use

• Problem:– not all servers detect when included file has changed

– to force re-compilation: change modification date of main file• Unix touch command• by explicitly modifying comment in main file such as:

<%-- Navbar.jsp modified 03/01/03 --%><%@ include file="Navbar.jsp" %>

• See also jsp:include element

48

95

CommunicationSoftware

2009-2010

© The Authors

The taglib Directive

• Allows developers to define their own JSP tags

• Developer defines interpretation of:– tag

– its attributes

– its body

• Custom tags can be grouped into tag libraries

• Components needed for using a custom tag library– tag handler classes (java) or tag files (JSP)

• defines the behaviour associated to the tags– tag library descriptor file (XML; file has .tld extension)

• info about the library and about each of its tags

– JSP files• that use the tag library

96

CommunicationSoftware

2009-2010

© The Authors

Actions < jsp: action attributes >

• Tags interpreted at execution time

– jsp:include

– jsp:forward

– jsp:param

– jsp:useBean

– jsp:setProperty

– jsp:getProperty

– jsp:plugin

– jsp:params

– jsp:fallback

JavaBeans tags

HTML <object> tags

49

97

CommunicationSoftware

2009-2010

© The Authors

The jsp:include Action

• Adds content of specified file when request treated– therefore, after translation to servlet

• Required attributes of include :– page : a relative URL (JSP expressions can be used)

– flush :• value is " true " : any buffered content flushed to browser• JSP 1.1: value " true " was mandatory

• Included files– normally text or HTML files

– cannot contain JSP constructs

– may be result of resources that use JSP to generate output• thus, URL may point to JSP or servlets

98

CommunicationSoftware

2009-2010

© The Authors

The jsp:forward Action

• Contents generated by the indicated JSP or servlet– added to the response

• Control does not come back to original page– stays with the forward page

• Attributes:– page : a relative URL

• Interaction with output buffering (c.f. page directive, buffer attr.):– forwarding leads to output buffer being cleared

– forwarding after output has been sent to browser: exception• e.g. no buffer and some output sent• e.g. buffer size exceeded and buffer defined as autoflush

• Example:<jsp:forward page="list.jsp" />

50

99

CommunicationSoftware

2009-2010

© The Authors

The jsp:param Action

• For specifying parameters of passed-on request– temporarily add new, or override existing, request param.– retrieved with request.getParameter

• Attributes– name: name of the parameter– value : parameter value (JSP expressions can be used)

• Examples:<jsp:include page=“header.jsp” flush=“true”>

<jsp:param name=“title” value=“Welcome” /></jsp:include>

<jsp:forward page=“list.jsp”><jsp:param name=“order” value=“A380” />

</jsp:forward>

100

CommunicationSoftware

2009-2010

© The Authors

JSP XML Syntax

• Script elements

– expressions<jsp:expression> Expression </jsp:expression>

– scriptlets<jsp:scriptlet> scriptlet code </jsp:scriptlet>

– declarations<jsp:declaration> declarations </jsp:declaration>

• Directives<jsp:directive:directiveName attribute_list />

• Template Data<jsp:text> text </jsp:text>

51

101

CommunicationSoftware

2009-2010

© The Authors

Example 4: Simple JSP

<%@ page language= “ java ”contentType= “ text/html;charset=iso-8859-1 ” %>

<%@ page import= “ java.util.Date ” %>

<html><head>

<title>Hola Mundo</title></head><body>

<%! private int accessCount = 0; %>

<p>Hello, this is a JSP.</p><p>The time on the server is <%= new Date() %>.</p><p>This page has been accessed <%= ++accessCount %>

times since server start-up.</p>

</body></html>

102

CommunicationSoftware

2009-2010

© The Authors

Example 4: Simple JSP Compiled to Servlet(Tomcat 5.x)

import java.util.Date;

public class hello_jsp extends HttpJspBase {

private int accessCount = 0;

public void _jspService(HttpServletRequest request,HttpServletResponse response)

throws ServletException, IOException {

. . .response.setContentType("text/html;charset=iso-8859 -1");pageContext = _jspxFactory.getPageContext(this, req uest,

response, null, true, 8192, true);out = pageContext.getOut();out.write("\r\n");out.write("<html><head><title>Hola Mundo</title></he ad>\r\n");out.write(" <body>\r\n");out.write(" <p>Hello, this is a JSP.</p>\r\n");out.write(" <p>The time on the server is " + new D ate() + ".</p>\r\n");out.write(" <p>This page has been accessed " + ++a ccessCount );out.write(" times since server start-up.</p>\r\n ");out.write("</body></html>\r\n");. . .

}}

52

103

CommunicationSoftware

2009-2010

© The Authors

Ejemplo 4: Server Response

Hello, this is a JSP

The time on the server is Tue Oct 16 21:58:11 CEST 2007

This page has been accessed 3 times since server start-up

104

CommunicationSoftware

2009-2010

© The Authors

Java Beans

• All data fields private: called properties

• Reading/writing bean data– getXxx method (accessor)

– setXxx method (mutator)

• Events– beans can send notifications of property changes

• Introspection– self-knowledge

• Serializability

• Customisation– property editors

53

105

CommunicationSoftware

2009-2010

© The Authors

Why Use JavaBeans?

• Reusability and modularity– seperate java classes

• easier to write, compile, test, debug and reuse

– instead of large quantities of code embedded in JSP pages

• Clear separation between content and presentation – java objects manipulated using XML-compatible syntax

• Easier to share objects between JSPs and servlets

• Can be used to simplify the process of reading request parameters

106

CommunicationSoftware

2009-2010

© The Authors

The jsp:useBean Action

<jsp:useBean id="name" class="package.Class" />

• Meaning:– instantiate an object of the class indicated in the class attribute

– bind it to a variable whose name is indicated in the id attribute

• Alternative– use the beanName attribute instead of the class attribute

– the beanName attribute can refer to a file containing a serialized Bean

• Accessing properties:<jsp:getProperty name="book1" property="title" />

is equivalent to:<%= book1.getTitle() %>

• Assigning to properties:<jsp:setProperty name="book1" property="title"

value="Bible" />

is equivalent to:<%= book1.setTitle("Bible") %>

54

107

CommunicationSoftware

2009-2010

© The Authors

The jsp:setProperty Action (1/2)

• Usually, attribute values must be strings– JSP expressions can be used in the attributes: name, value

• Example:– setting a property to the value of a request parameter:

<jsp:setProperty name="entry"property="itemID"value='<%= request.getParameter("itemID") %>' />

• Problem: what happens if the property is not of type String ?– explicit type conversion (inside try-catch ), but…

… see next slide

108

CommunicationSoftware

2009-2010

© The Authors

The jsp:setProperty Action (2/2)

• Associating value of property to that of request parameter

– parameter and property have different names:<jsp:setProperty name="customer" property="email"

param="new_email" />

is equivalent to customer.setEmail(request.getParameter("new_email")

– parameter and property have identical names:<jsp:setProperty name="customer" property="email" / >

is equivalent tocustomer.setEmail(request.getParameter("email")

• Associating values of all properties with identically-named request parameters:

– <jsp:setProperty name="customer" property="*" />

• In these cases, type conversion is automatic

55

109

CommunicationSoftware

2009-2010

© The Authors

Example 5: Simple Bean

// Source: “Core Servlets…”, Marty Hall et al

package coreservlets;

public class StringBean {private String message = "No message specified";

public String getMessage() {return(message);

}

public void setMessage(String message) {this.message = message;

}}

110

CommunicationSoftware

2009-2010

© The Authors

Example 5: JSP Including Simple Bean

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transit ional//EN"><html>

<head><title>Using JavaBeans with JSP</title>

<link rel="stylesheet" href="JSP-Styles.css" type=" text/css" />

</head>

<body>

<table border="5" align="center">

<tr><th class="title">Using JavaBeans with JSP</th> </tr></table>

<jsp:useBean id="messageBean" class="coreservlets.M essageBean" />

<ol>

<li>Initial value (print with getProperty):

<i> <jsp:getProperty name="messageBean" property="messa ge" /> </i></li>

<li>Initial value (print with JSP expression):

<i> <%= messageBean.getMessage() %> </i></li>

<li> <jsp:setProperty name="messageBean" property="messa ge" value="Best

message bean: Fortex" />

Value after setting property with setProperty (print with getProperty):

<i> <jsp:getProperty name="messageBean" property="messa ge" /> </i></li>

<li> <% messageBean.setMessage("My favorite: Kentucky Wo nder"); %>

Value after setting property with scriptlet (print w ith JSP expression):

<i> <%= messageBean.getMessage() %> </i></li>

</ol>

</body>

</html>

56

111

CommunicationSoftware

2009-2010

© The Authors

Example 5: Server Response

112

CommunicationSoftware

2009-2010

© The Authors

Bean Scope

• In the JSP context– beans created with jsp:useBean

– bound to a local variable

– four possibilities regarding their storage location• scope attribute

57

113

CommunicationSoftware

2009-2010

© The Authors

Bean Scope

Attribute scope of action jsp:useBean takes one of values:

• page (default value).– placed in pageContext object for duration of current request

– accessible through predefined variable pageContext

• request

– stored in the ServletRequest object

– accessible through predefined variable request

• session

– stored in the HttpSession

– accessible through predefined variable session

• application

– stored in the ServletContext object

– accessible through predefined variable application

114

CommunicationSoftware

2009-2010

© The Authors

Bean Scope

58

115

CommunicationSoftware

2009-2010

© The Authors

Conditional Creation of Beans

• The jsp:useBean action– instantiates new bean if no bean with same id & scope found

– otherwise, existing bean associated to variable referenced by id

• If, instead of:<jsp:useBean … />

we write:<jsp:useBean … >

sentences</jsp:useBean>

then sentences are executed only when new bean created– convenient for setting initial bean properties for shared beans

– all pages that share the bean have the initialisation code

116

CommunicationSoftware

2009-2010

© The Authors

Expression Language (EL)

• First introduced with JSTL (Java Standard Tag Library)

– later extended for use anywhere (outside JSTL tags): JSP 2.0 EL

• Facilitates writing scriptlets in JSP pages

• Syntax: ${expression}

– an EL expression may be escaped (& not evaluated) with \

• EL expressions may be used– as values of attributes in actions, e.g.

<jsp:include page= " ${location} " >

– inside the text of a template, such as HTML, e.g.<h1>Welcome ${name}</h1>

• Example– set attribute (in this case in a servlet)

request.setAttribute("endMessage","That's all Folks !");

– use attribute in JSP (four scopes searched for attribute):<h2>${endMessage}</h2>

59

117

CommunicationSoftware

2009-2010

© The Authors

JSP Standard Tag Library (JSTL)

• JSTL is a standardised set of tag libraries – encapsulates JSP functionality common to many applications

• Syntax<prefix:tagName (attributeName= “ attributeValue ” )* />

<prefix:tagName>body</prefix:tagName>

• Functional areas:

fnhttp://java.sun.com/jsp/jstl/functionsFunctions

sqlhttp://java.sun.com/jsp/jstl/sqlRelational database access

fmthttp://java.sun.com/jsp/jstl/fmtFormatting / internationalisation

xhttp://java.sun.com/jsp/jstl/xmlXML processing

chttp://java.sun.com/jsp/jstl/coreCore

PrefixURIArea

118

CommunicationSoftware

2009-2010

© The Authors

Some of the JSTL Core Tags (1/2)

• set

– creates an EL variable

– updates value of existing EL variable or of JavaBean property<c:set [var="varName“] [value="value"]

[scope="{page|request|session|application}"]

[target="variable.bean"][property="bean.property"] />

• remove

– deletes an EL variable<c:remove var="varName"

[scope="{page|request|session|application}"] />

• url

– provides an encoded (relative) URL, if cookies are disabled (forsession management purposes)<c:url [value="value"] [var="varName" ] [context= "some"]

[scope="{page|request|session|application}"] />

60

119

CommunicationSoftware

2009-2010

© The Authors

Some of the JSTL Core Tags (2/2)

• if (see also tags choose / when / otherwise )<c:if test= " expression " [var= " varName “]

[scope= " {page|request|session|application} " ] >

body if expression is true</c:if>

• forEach

– iteration over the content of the tag<c:forEach items= " collection " [var= " varName " ] [ … ]>

body content</c:forEach>

• out

– evaluates an expression and writes results in current JSPWriter<c:out value= " value " [default= " defaultValue " ]

[escapeXml= " {true|false} " ] />

CommunicationSoftware

2009-2010

© The Authors

Example 6: JSTL and EL

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<c:if test="${not empty errorMsgs}" ><p>Please correct the following errors:

<ul><c:forEach var="message" items="${errorMsgs}">

<li>${message}</li></c:forEach>

</ul></p>

<p>Accessing messageBean properties: ${messageBean.message}</p>

</c:if>

previously stored in one of the objects: pageContext , request , session , or application

previously stored in one of the objects: pageContext , request , session , or application

61

121

CommunicationSoftware

2009-2010

© The Authors

Presentation tier:Integration of Servlets and JSPs

122

CommunicationSoftware

2009-2010

© The Authors

Contents: Integration of Servlets and JSPs

• Integration de servlets and JSPs

• Handling a single request

• Forwarding in servlets and JSPs

• The MVC design pattern

62

123

CommunicationSoftware

2009-2010

© The Authors

Integration of Servlets and JSP

• Advantage of JSP over servlets– easier to generate the static part of the HTML

• Problem– JSP document provides a single overall presentation

• Solution– combine servlets and JSP

– servlet:• handles initial request• partially processes data• configures the beans• passes results to one of a number of different JSP pages

depending on circumstance

124

CommunicationSoftware

2009-2010

© The Authors

Handling a Single Request

• Servlet-only solution suitable when– output is a binary type or there is no output

– format/layout of the page is highly variable

• JSP-only solution suitable when– output is mostly character data

– format/layout mostly fixed

• Servlet & JSP combination solution suitable when– single request has several possible responses, each with

different layout

– business logic and Web presentation not developed by same people

– application performs complicated data processing but has relatively fixed layout

63

125

CommunicationSoftware

2009-2010

© The Authors

Forwarding in Servlets and JSPs

• From a JSP (unusual)<jsp:forward page='login.jsp'><jsp:param name='login' value='pepe' /></jsp:forward>

• From a ServletRequestDispatcher rd =

getServletContext().getRequestDispatcher("login.jsp?login=pepe");

rd.forward(request, response);

LoginServletLoginServlet

LoginServlet?login=pepeLoginServlet?login=pepe

126

CommunicationSoftware

2009-2010

© The Authors

Example 1: Request Forwarding

public void doGet(HttpServletRequest request,HttpServletResponse response)

throws ServletException IOException {

String operation = request.getParameter("operation" );if (operation == null) {

operation = "unknown";}

String address;if (operation.equals("order")) {

address = "/WEB-INF/Order.jsp";else if (operation.equals("cancel")) {

address = "/WEB-INF/Cancel.jsp";else

address = "/WEB-INF/UnknownOperation.jsp";}

RequestDispatcher dispatcher =

request.getRequestDispatcher(address);dispatcher.forward(request, response);

}

64

127

CommunicationSoftware

2009-2010

© The Authors

Model-View-Controller (MVC) Pattern

• Design Pattern (such as MVC) – repeatable solution to commonly-occurring software problem

• MVC pattern well suited when– single request can result in responses with different format– several pages have substantial common processing

• Model– the data to be manipulated and displayed

• View– the actual display

• Controller– handles the request– decides what logic to invoke– decides which view applies

128

CommunicationSoftware

2009-2010

© The Authors

MVC Pattern: More Detail

Source: Java BluePrints, Model-View-Controller. Available at:http://java.sun.com/blueprints/patterns/MVC-detaile d.html

65

129

CommunicationSoftware

2009-2010

© The Authors

MVC is an Architectural Pattern

Database

Also denoted “Model 2”

Client

Browser

Web server

Container

Controller

HTTP request

HTTP response view

HTTP<%

%>

Source: Web Component Development Wth Servlet and JSP TechnologiesSun Microsystems (course SL-314-EE5)

130

CommunicationSoftware

2009-2010

© The Authors

Implementing MVC with Request Dispatcher

1. Define beans to represent the data

2. Servlet handles requests– reads request params & checks for missing/malformed data

3. Servlet populates beans– servlet invokes business logic / data-access code (simple cases:

may be bean methods); obtains results– results stored in beans (only servlet creates and modifies beans)

4. Servlet stores beans– invokes setAttribute on request, session or context

5. Servlet forwards request to appropriate JSP page– uses forward method of request dispatcher

6. JSP extracts data from beans– uses jsp:usebean and jsp:getProperty

– or uses JSP 2.0 EL: more powerful, concise, readable

66

131

CommunicationSoftware

2009-2010

© The Authors

Implementing MVC

2

3

4

5

6

Source: IBM Labs. JSP – Dynamic Content Generation Made Simple

132

CommunicationSoftware

2009-2010

© The Authors

Example: Web Application with JSP

• Using only JSP

• For larger web applications, use MVC:– JSP for the presentation

– servlets for the logic

login.jsp validate_login.jsp welcome.jsp

POST(login,password) forward()

if (login,failed) then forward()

67

133

CommunicationSoftware

2009-2010

© The Authors

Example: Web Application using MVC

login.jsp

list.jsp welcome.jsp

loginservlet

productservlet

if (login failed) then forward(login)

POST(login,password)

if (not logged) then forward()

forward(ListBean)

GET(productId) GET()

forward(ProductBean)

DB

session.setAttribute(UserInfoBean)

134

CommunicationSoftware

2009-2010

© The Authors

Handling Beans in Servlets and JSPs

• JSP:<!–- instantiate/use bean --><jsp:useBean id='user' class='UserInfoBean' scope=' session'>

<jsp:setProperty name='user' property='lastName' va lue='Perez' /></jsp:useBean><!–- set property --><jsp:setProperty name='user' property='firstName' v alue='Pepe'><!–- get property --><jsp:getProperty name='user' property='firstName' / >

• Servlet:// instantiate/use bean

UserInfoBean user = (UserInfoBean) session.getAttri bute("user");if (user == null) {

user = new UserInfoBean();user.setLastName("Perez");session.setAttribute("user", user);

}// set propertyuser.setFirstName = "Pepe";// get propertyout.println(user.getFirstName());

68

135

CommunicationSoftware

2009-2010

© The Authors

MVC: Handling Beans in JSPs

• MVC: bean is initialised in servlet and used in JSP

– using bean in JSP without the EL:<!–- use bean --><jsp:useBean id='user' class='UserInfoBean' scope='s ession' /><!–- get property --><jsp:getProperty name='user' property='firstName' />

– using bean in JSP with JSTL EL<!–- use bean and get property -->

<c:out value="${user.firstname}" />

– using bean in JSP with JSP 2.0 EL:<!–- use bean and get property -->${user.firstname}

136

CommunicationSoftware

2009-2010

© The Authors

MVC: Passing Data on Forward

• Destination obtains unprocessed info from request object, but – programming easier in origin servlet than destination JSP

– multiple JSPs may require the same data

• Simple value: pass as attribute of request object, e.g.– at origin

request.setAttribute(“key1”, value1);

– at targetType1 value1 = (Type1) request.getAttribute(“key1”) ;

or as parameter of forward action

• Complex value: represent as shared bean– scope = application : stored in servletContext object– scope = session : stored in session object

– scope = request : stored in request object

69

137

CommunicationSoftware

2009-2010

© The Authors

Other Topics of Interest

• Lifecycle listeners: – monitor and react to events in a servlet's life cycle

• Filtering API: Filter , FilterChain , FilterConfig

– filter: an object that can transform the header and content (or both) of a request or response (from servlet 2.3)

– authentication, logging, image conversion, data compression, encryption, tokenizing streams, XML transformations,…

• Java Server Faces– Java/JSP-based Web application framework that simplifies the

development of user interfaces for Java EE applications

• Jakarta Struts– open-source framework that extends the Java Servlet API to

facilitate development of Web applications conforming to the MVC pattern.

138

CommunicationSoftware

2009-2010

© The Authors

On-line Bibliography

• Sun's servlet pages / JSP pages / JSTL pageshttp://java.sun.com/products/servlet/

http://java.sun.com/products/jsp/

http://java.sun.com/products/jsp/jstl/

• Marty Hall's book Core Servlets and JavaServer Pages, vol. 1, 2nd editionhttp://pdf.coreservlets.com/

• Marty Hall's book More Servlets and JavaServer Pages, 1st edition(including information on filters and lifecycle listeners)http://pdf.moreservlets.com/

• Marty Hall's slides Beginning and Intermediate-Level Servlet, JSP and JDBC Tutorialshttp://courses.coreservlets.com/Course-Materials/cs ajsp2.html

• Apache Tomcat home page / Marty Hall's Apache Tomcat tutorialhttp://tomcat.apache.org/

http://www.coreservlets.com/Apache-Tomcat-Tutorial/

• Sun's Java Server Faces Technology pageshttp://java.sun.com/javaee/javaserverfaces/

• Jakarta Strutshttp://struts.apache.org/