dynamic content generation

82
Dynamic content generation Eleonora Ciceri [email protected]

Upload: eleonora-ciceri

Post on 10-May-2015

3.596 views

Category:

Technology


0 download

TRANSCRIPT

Page 1: Dynamic content generation

Dynamic content generation Eleonora Ciceri

[email protected]

Page 2: Dynamic content generation

Dynamic content generation

¤  Motivations ¤  User needs cannot be satisfied by using just static content.

The following is needed too:

¤  Data coming from databases

¤  Response to specific requests (e.g., queries)

¤  Client-side scripting does not achieve the required results in dynamic data gathering

¤  Solution ¤  Server-side architectures that generate content dynamically

Page 3: Dynamic content generation

HTTP basics

Page 4: Dynamic content generation

HTTP basics

¤  HTTP is a stateless protocol: ¤  The client performs the request

¤  The web server responds and the transaction is done

¤  Each request is associated with a method, that specifies the type of action the client wants performed

¤  Available methods: ¤  GET

¤  POST

¤  Others: HEAD, PUT, DELETE, TRACE, OPTIONS

Page 5: Dynamic content generation

GET method

¤  The GET method is designed for getting information (e.g., a document, a chart, the result of a database query)

¤  The request contains some information that describes what the user wants (e.g., coordinates x,y for a chart)

¤  This information is collected in the query string, passed as a sequence of characters appended to the request URL

http://my.server/page?par1=val1&par2=val2

Query string

Page 6: Dynamic content generation

POST method

¤  The POST method is designed for posting information (a credit card number, information that has to be stored in a database)

¤  A POST request passes all its data, of unlimited length, as part of its HTTP request body

¤  The exchange is invisible to the client ¤  POST requests cannot be bookmarked or reloaded

Page 7: Dynamic content generation

POST method: form

<form method=POST action="my.page">!!Tell me your name:!!<input type="text" name="username"/>!!<input type="submit" value="Submit"/>!

</form>!

This information will be sent to the server

Specify the method

Page 8: Dynamic content generation

Other request methods

¤  HEAD: sent by a client when it wants to see only the headers of the response ¤  Why? To determine document size, modification time, general

availability

¤  PUT: used to place documents directly on the server

¤  DELETE: used to remove documents from the server

¤  TRACE: returns to the client the exact content of its request (used for debugging purposes)

¤  OPTIONS: used to ask the server which methods it supports

Page 9: Dynamic content generation

Java Servlets Basic concepts

Page 10: Dynamic content generation

Why do we use Java?

¤  Cross-platform: useful in case of a heterogeneous collection of servers (Unix/Windows operating systems)

¤  Object-oriented

¤  Support for networking and enterprise APIs

Page 11: Dynamic content generation

Servlets

¤  A servlet is a small, pluggable extension to a server that enhances the server’s functionality ¤  Applications: web server, mail server, application server…

¤  A servlet runs inside a JVM (Java Virtual Machine) on the server

¤  Advantages ¤  Support for Java is required on servers (not in web browsers)

¤  Servlets are portable (across operating systems and web servers)

Page 12: Dynamic content generation

Servlet container

¤  A servlet container is a component of the server that interacts with Java servlets

¤  It is responsible for: ¤  managing the lifecycle of the servlets

¤  mapping a URL to a particular servlet

HTTP request parameters

response HTTP response

Page 13: Dynamic content generation

Persistence

¤  Servlets are all handled by separate threads within the web server process ¤  A single object instance is stored in the server’s memory

¤  Advantages of reusing processes: ¤  Servlets create stateful applications by storing information

about the user session

¤  Resources are shared, e.g., database connections

Request for Servlet1

Request for Servlet2

Request for Servlet1

thread

thread

thread

Page 14: Dynamic content generation

The Servlet API

¤  Servlets use classes and interfaces from two packages ¤  javax.servlet: contains classes to support generic servlets

(protocol-independent)

¤  javax.servlet.http: adds HTTP-specific functionality

¤  Every servlet implements the javax.servlet.Servlet interface ¤  javax.servlet.GenericServlet is a protocol-

independent servlet

¤  javax.servlet.http.HttpServlet is an HTTP servlet

Page 15: Dynamic content generation

GenericServlet

¤  This servlet overrides the service() method to handle requests, taking as inputs: ¤  The request object ¤  The response object

request

response

Page 16: Dynamic content generation

HttpServlet

¤  This servlet overrides the doGet() and doPost() methods to handle GET and POST requests, respectively

¤  The service() method handles the setup and dispatching to all the doXXX() methods ¤  Do NOT override this method!

GET request

GET response

POST request

POST response

Page 17: Dynamic content generation

Servlet life cycle

¤  Servlet’s initialization: when the server starts, the servlet’s init() method is called

¤  Handle requests: when a request is captured by the server, the servlet’s service(), doGet() and doPost() methods are called according to the request type

¤  Servlet’s destruction: when the server process is stopped, the servlet’s destroy() method is called and the garbage collection is performed

Page 18: Dynamic content generation

Java Servlets Basic coding using Java Servlet API

Page 19: Dynamic content generation

Hello World! servlet

import java.io.*;!import javax.servlet.*;!import javax.servlet.http.*;!!public class HelloWorldServlet extends HttpServlet {!

!public void doGet(HttpServletRequest request, HttpServletResponse response)!! ! ! !throws ServletException, IOException {!! !response.setContentType("text/html");!! !PrintWriter out = response.getWriter();!! !!! !out.println("<HTML>");!! !out.println("<HEAD><TITLE>Hello World Servlet</TITLE></HEAD>");!! !out.println("<BODY>");!! !out.println("Hello, World!");!! !out.println("</BODY>");!! !out.println("</HTML>");!! !out.close();!!}!

}

Page 20: Dynamic content generation

import java.io.*;!import javax.servlet.*;!import javax.servlet.http.*;!!public class HelloWorldServlet extends HttpServlet {!

!public void doGet(HttpServletRequest request, HttpServletResponse response)!! ! ! !throws ServletException, IOException {!! !response.setContentType("text/html");!! !PrintWriter out = response.getWriter();!! !!! !out.println("<HTML>");!! !out.println("<HEAD><TITLE>Hello World Servlet</TITLE></HEAD>");!! !out.println("<BODY>");!! !out.println("Hello, World!");!! !out.println("</BODY>");!! !out.println("</HTML>");!! !out.close();!!}!

}

Hello World! servlet

HTTP servlet interface

Packages

Page 21: Dynamic content generation

import java.io.*;!import javax.servlet.*;!import javax.servlet.http.*;!!public class HelloWorldServlet extends HttpServlet {!

!public void doGet(HttpServletRequest request, HttpServletResponse response)!! ! ! !throws ServletException, IOException {!! !response.setContentType("text/html");!! !PrintWriter out = response.getWriter();!! !!! !out.println("<HTML>");!! !out.println("<HEAD><TITLE>Hello World Servlet</TITLE></HEAD>");!! !out.println("<BODY>");!! !out.println("Hello, World!");!! !out.println("</BODY>");!! !out.println("</HTML>");!! !out.close();!!}!

}

Hello World! servlet

Request object Response object

Page 22: Dynamic content generation

import java.io.*;!import javax.servlet.*;!import javax.servlet.http.*;!!public class HelloWorldServlet extends HttpServlet {!

!public void doGet(HttpServletRequest request, HttpServletResponse response)!! ! ! !throws ServletException, IOException {!! !response.setContentType("text/html");!! !PrintWriter out = response.getWriter();!! !!! !out.println("<HTML>");!! !out.println("<HEAD><TITLE>Hello World Servlet</TITLE></HEAD>");!! !out.println("<BODY>");!! !out.println("Hello, World!");!! !out.println("</BODY>");!! !out.println("</HTML>");!! !out.close();!!}!

}

Hello World! servlet

Set the standard MIME type for HTML pages

A MIME type identifies the file formats on the internet

A MIME type is used to understand how to interpret a file/an attachment

Page 23: Dynamic content generation

import java.io.*;!import javax.servlet.*;!import javax.servlet.http.*;!!public class HelloWorldServlet extends HttpServlet {!

!public void doGet(HttpServletRequest request, HttpServletResponse response)!! ! ! !throws ServletException, IOException {!! !response.setContentType("text/html");!! !PrintWriter out = response.getWriter();!! !!! !out.println("<HTML>");!! !out.println("<HEAD><TITLE>Hello World Servlet</TITLE></HEAD>");!! !out.println("<BODY>");!! !out.println("Hello, World!");!! !out.println("</BODY>");!! !out.println("</HTML>");!! !out.close();!!}!

}

Hello World! servlet

Requires the writer on which the output will be printed

Page 24: Dynamic content generation

import java.io.*;!import javax.servlet.*;!import javax.servlet.http.*;!!public class HelloWorldServlet extends HttpServlet {!

!public void doGet(HttpServletRequest request, HttpServletResponse response)!! ! ! !throws ServletException, IOException {!! !response.setContentType("text/html");!! !PrintWriter out = response.getWriter();!! !!! !out.println("<HTML>");!! !out.println("<HEAD><TITLE>Hello World Servlet</TITLE></HEAD>");!! !out.println("<BODY>");!! !out.println("Hello, World!");!! !out.println("</BODY>");!! !out.println("</HTML>");!! !out.close();!!}!

}

Hello World! servlet

Print the web page HTML code

Page 25: Dynamic content generation

Hello World! servlet results

Servlet’s path: project path + servlet’s name

Printed content

Page 26: Dynamic content generation

Configure a web application

¤  A web application is made of a set of servlets that are stored in a project

¤  The description of the web application content is contained in the web.xml file

¤  This file contains: ¤  The description of each servlet (name, class)

¤  The mapping of the servlet (used to reference the servlet when accessing to the server)

Page 27: Dynamic content generation

Configuration file for HelloWorldServlet

<web-app> !!<servlet>!! !<servlet-name>!! ! !HelloWorldServlet!! !</servlet-name>!! !<servlet-class>!! ! !it.polimi.tiw.examples.HelloWorldServlet!! !</servlet-class>!!</servlet>!!<servlet-mapping>!! !<servlet-name>!! ! !HelloWorldServlet!! !</servlet-name>!! !<url-pattern>!! ! !/HelloWorld!! !</url-pattern>!!</servlet-mapping>!

</web-app>

Container for the servlets’ descriptions

Mapping to a specific path on the server

Page 28: Dynamic content generation

Java Servlets Input and output

Page 29: Dynamic content generation

Read information from the client

¤  Information is received from the client by reading the data included in HttpServletRequest

¤  Input stream methods ¤  getReader(): retrieves the body of the request ¤  getContentType(): retrieves the request content type ¤  getContentLength(): retrieves the request content length

¤  Header reading methods ¤  getHeader(name): retrieves the name HTTP header ¤  getHeaders(name): retrieves the name HTTP header as a

collection of String objects

Page 30: Dynamic content generation

Read information from the client

¤  Parameters reading methods ¤  getParameter(name): reads the parameter name from the

request ¤  getParameterValues(name): reads an array of String objects

containing all the values the name parameter has ¤  getParameterNames(): returns the names of all the parameters

contained in this request ¤  getQueryString(): reads the query string

¤  Client information retrieval methods ¤  getRemoteAddr(): reads the IP address ¤  getRemoteHost(): reads the fully qualified name of the client

Page 31: Dynamic content generation

Send information to the client

¤  Information is sent to the client by modifying the data included in HttpServletResponse

¤  Output stream methods ¤  getWriter(): gets the writer on which the output is printed

¤  setContentLength(cl): sets the content length equal to cl

¤  setContentType(ct): sets the content type equal to ct

¤  Header editing methods ¤  setHeader(String name, String value): sets the value of

the HTTP header name equal to value

Page 32: Dynamic content generation

Send information to the client

¤  Error handling methods ¤  setStatus(int s): set the status of the transaction equal to s

¤  sendError(int s): sends the error to the server, who is in charge of handling it

¤  Redirect methods ¤  sendRedirect(String location): sends a temporary redirect

response to the client using the specified location URL

Page 33: Dynamic content generation

Handling forms data

¤  We will send the user’s name via an HTML form, so that it will be displayed by the servlet

¤  The request can be sent using either the GET or the POST methods

HelloWorldForm.html

userName

Page 34: Dynamic content generation

Sending via the GET method: form

<html>!!<head>!! <title>Meet the user</title>!!</head>!!<body>!! <form method=GET action="/SlidesExamples/HelloWorldFormServlet">!! !Tell me your name:!! !<input type="text" name="userName"/>!! !<input type="submit" value="Submit"/>!! </form>!!</body>!

</html>

Servlet’s path

Parameter’s name

FINAL URL: http://my.server:8080/SlidesExamples/HelloWorlFormServlet?userName=name

Query string

Page 35: Dynamic content generation

Sending via the GET method: servlet

public class HelloWorldFormServlet extends HttpServlet {!public void doGet(HttpServletRequest request, HttpServletResponse response)!

! ! ! !throws ServletException, IOException {!response.setContentType("text/html");!PrintWriter out = response.getWriter();!

! !!String userName = request.getParameter("userName");!if (userName.equals(""))!

!userName = "World";!! !!

out.println("<HTML>");!out.println("<HEAD><TITLE>Hello World Servlet</TITLE></HEAD>");!out.println("<BODY>");!out.println("Hello, " + userName + "!");!out.println("</BODY>");!out.println("</HTML>");!out.close();!

}!}

Retrieve parameter from the request

When the user leaves the input field empty, the parameter is empty too

Print the request parameter

Page 36: Dynamic content generation

Sending via the POST method

¤  We want the same behavior with POST as we had for the GET; thus, we dispatch all POST requests to the doGet() method

¤  In general, it is better if a servlet implements either doGet() or doPost()

public void doPost(HttpServletRequest request, ! ! ! !HttpServletResponse response)!! !throws ServletException, IOException {!!doGet(request, response);!

}!

Page 37: Dynamic content generation

Java Servlets Instance persistence

Page 38: Dynamic content generation

Instance persistence

¤  Servlets persist between requests as object instances

¤  Advantage: a servlet has already loaded anything it’s likely to need during the handling of a request ¤  Database connections

¤  Shopping cart

¤  Cached pages

¤  …

Page 39: Dynamic content generation

A simple counter

public class SimpleCounter extends HttpServlet {!!!

int count;!!!

public void init() throws ServletException {!!count = 0;!

}!!!

public void doGet(HttpServletRequest request, HttpServletResponse response)!

! ! !throws ServletException, IOException {!!response.setContentType("text/plain");!!PrintWriter out = response.getWriter();!! !!!count++;!!out.println("Since loading this servlet has been accessed " + !count + " times");!

}!}

When the server loads the servlet as a single instance, the counter is initialized

Every request is handled by this single instance

Each request increments the counter

Page 40: Dynamic content generation

A simple counter: results

¤  The same instance variable exists between invocations and for all invocations

¤  Every time the page is loaded, the counter is incremented

Page 41: Dynamic content generation

Synchronization

¤  Each of the client threads has the ability to manipulate a servlet’s non local variable ¤  Result: inconsistencies, data corruption

Request1

Request2

count = 0

count = 1

count = 2

The answer is 2 for both the responses!

This happens because the servlets are concurrently modifying the same variable, thus the second request modifies the count before the first thread prints the count Thread1.print()

Thread2.print()

Page 42: Dynamic content generation

Synchronization

¤  To prevent this problem one can add one or more synchronized blocks to the code ¤  Anything inside a synchronized block is guaranteed not to

be executed concurrently by another thread

¤  When a thread wants to modify what is inside a synchronized block, it has to obtain a monitor

¤  If another thread has the monitor, the first thread must wait

Page 43: Dynamic content generation

Synchronization – First solution

public class SyncCounter extends HttpServlet{ !int count = 0;!!public void doGet(HttpServletRequest request, HttpServletResponse response) !

! !throws ServletException, IOException {!response.setContentType("text/plain"); !PrintWriter out = res.getWriter(); !synchronized(this) {!

count++; !out.println("Since loading, this servlet has been accessed " + count + " times.");!

}!}!

}

This block requires a monitor in order to be executed

Page 44: Dynamic content generation

Synchronization – Other solutions

¤  Add synchronized to the doGet() signature public synchronized void doGet(HttpServletRequest request, HttpServletResponse response)!

¤  Make the synchronized block as small as possible using a local variable int local_count;!synchronized(this) {!

local_count = ++count;!}!out.println(“Number of accesses: ” + local_count);!

Page 45: Dynamic content generation

Class count

A holistic counter public class HolisticCounter extends HttpServlet {!

static int classCount = 0;!int count;!static Hashtable<HolisticCounter, HolisticCounter> instances= new Hashtable<HolisticCounter, HolisticCounter>();!

!!public void init() throws ServletException {!

count = 0;!} !!public void doGet(HttpServletRequest request, HttpServletResponse response)!

! ! !throws ServletException, IOException {!response.setContentType("text/plain");!PrintWriter out = response.getWriter();!

! !!count++;!out.println("This servlet instance has been accessed " + count + " times.");!

! !!instances.put(this, this);!out.println("There are currently " + instances.size() + " instances.");!

! !!classCount++;!out.println("Across all instances, this servlet has been accessed " + classCount + " times.");!

}!!}

Instance count

Store instances

Page 46: Dynamic content generation

Java servlets Init and context parameters

Page 47: Dynamic content generation

Init parameters

¤  Init parameters are available in the context of a servlet

¤  Init parameters’ purpose is twofold ¤  Specify initial values or default values for servlet variables

¤  Tell a servlet how to customize its behavior

¤  The initial values are stored in the web.xml file

ServletConfig object

web.xml

getInitParameter(“p1”)

getInitParameter(“p2”)

Init parameters

Page 48: Dynamic content generation

Init parameters

<servlet>!!<servlet-name>!! !InitCounter!!</servlet-name>!!<servlet-class>!! !it.polimi.tiw.examples.InitCounter!!</servlet-class>!!<init-param>!! !<param-name>!! ! !InitialCounterValue!! !</param-name>!! !<param-value>!! ! !100!! !</param-value>!! !<description>!! ! !Initial counter value!! !</description>!!</init-param>!

</servlet>

This is visible only to the InitCounter servlet

Name of the parameter that will be read from the configuration

Value for InitialCounterValue

Page 49: Dynamic content generation

Init parameters

public class InitCounter extends HttpServlet { !!int count = 0; !!public void init(ServletConfig config) throws ServletException {!

!super.init(config);!!String initialCounterValue = config.getInitParameter("InitialCounterValue");!!try {!

count = Integer.parseInt(initialCounterValue);!!}!!catch (NumberFormatException e) {!

count = 0;!!}!

} !!public void doGet(HttpServletRequest request, HttpServletResponse response)!

! !throws ServletException, IOException {!!response.setContentType("text/plain");!!PrintWriter out = response.getWriter();!! !!!count++;!!out.println("Since loading, with initialization, this servlet has been !accessed " + count + " times");!

}!}

Load the initial parameter

For allowing the access to config outside the init() method

Page 50: Dynamic content generation

Context parameters

¤  Context parameters are available in the entire scope of the web application

¤  Context parameters are stored in the web.xml file

ServletContext object

web.xml

getInitParameter(“p1”)

getInitParameter(“p2”)

Context parameters

Page 51: Dynamic content generation

Context parameters

<web-app> !!<context-param>!! !<param-name>!! ! !userName!! !</param-name>!! !<param-value>!! ! !Eleonora!! !</param-value>!! !<description>!! ! !Name of the user that is using the web application!! !</description>!!</context-param>

Context parameter declaration

Page 52: Dynamic content generation

Context parameters

public class HelloDefaultUserServlet extends HttpServlet {!!

private String userName;!!!

public void init(ServletConfig config) throws ServletException {!!ServletContext context = config.getServletContext();!!userName = context.getInitParameter("userName");!!if (userName == null)!

userName = "World";!}!

!!public void doGet(HttpServletRequest request, HttpServletResponse response)!

! !throws ServletException, IOException {!!response.setContentType("text/plain");!!PrintWriter out = response.getWriter();!

!!out.println("Hello, " + userName + "!");!!out.close();!

}!!}

Extract the context (ServletContext object)

Extract the context parameter “userName”

Page 53: Dynamic content generation

Java Servlets Session tracking

Page 54: Dynamic content generation

Motivations

¤  HTTP is a stateless protocol ¤  No way for a server to recognize that a sequence of

requests are from the same client

¤  Problem: shopping cart? Several interactions!

¤  Solution: the client introduces himself as it makes each request ¤  Unique identifier

¤  Additional information about its identity

Page 55: Dynamic content generation

User authorization

¤  One way to perform session tracking is to leverage the information that comes with user authorization ¤  When the client logs in, the username is available to a servlet

through getRemoteUser() ¤  The user is identified through her username and thereby

track her session

¤  Advantage: easy to implement, works also if the user uses different machines to log in

¤  Disadvantage: it requires each user to register for an account and then log in each time she visits the site

Page 56: Dynamic content generation

Hidden form fields

¤  Another way to perform session tracking is to add information to the form by inserting hidden fields, i.e., fields that contain information but that are not visible ¤  <INPUT TYPE=hidden NAME=“zip” VALUE=“834629”/>

¤  Advantage: ubiquity, support for anonymity, no special server requirements

¤  Disadvantage: it works only for a sequence of dynamically generated forms, it breaks down with static/emailed/bookmarked documents or browser shutdowns

Page 57: Dynamic content generation

Persistent cookies

¤  A cookie is a bit of information sent by a web server to a browser that can later be read back from that browser

¤  When the browser receives the cookie ¤  It saves the cookie ¤  It sends the cookie back to the server each time it accesses

a page on that server

¤  A cookie’s value can be set so as to uniquely identify the user ¤  Thus: cookies are used in order to track the session

Page 58: Dynamic content generation

Working with cookies

¤  A cookie is creating by specifying: ¤  The name of the cookie

¤  The value of the cookie

¤  Cookie(name, value)

¤  The cookie is attached to the response by using the method addCookie(cookie)

¤  Cookies are read from the request by using the method getCookies()

Page 59: Dynamic content generation

Saving the sessionId in a cookie

public class SessionIdCookie extends HttpServlet {!!

public void doGet(HttpServletRequest request, HttpServletResponse response) !throws ServletException, IOException {!

!response.setContentType("text/plain");!!PrintWriter out = response.getWriter();!! !!!String sessionId = null;!!Cookie[] cookies = request.getCookies();!!if (cookies != null)!

for (int i = 0; i < cookies.length; i++)!if (cookies[i].getName().equals("sessionId"))!

! !sessionId = cookies[i].getValue();!! !!!if (sessionId == null) {!

sessionId = new java.rmi.server.UID().toString();!Cookie cookie = new Cookie("sessionId", sessionId);!response.addCookie(cookie);!

!}!! !!!out.println("SessionId: " + sessionId);!!out.close();!

}!}

Retrieve cookies from the request

Look for the cookie containing the sessionId

If the needed cookie does not exist, we create the sessionId with a standard method and then store it in a new cookie

Page 60: Dynamic content generation

Other functions for handling cookies

¤  setMaxAge(int expiry) specifies the maximum age of the cookie (in seconds) before it expires

¤  setSecure(boolean flag) indicates whether the cookie should be sent only over a secure channel, such as SSL

¤  setComment(String comment) sets the comment field of the cookie, describing the intended purpose of it

Page 61: Dynamic content generation

URL rewriting (1)

¤  Every local URL the user might click is dynamically modified to include extra information

¤  You have to ask your servlet container to enable it

¤  Several ways of doing it

¤  Extra path information ¤  http://my.server:port/servlet/Rewritten/extraPath ¤  extraPath contains extra information ¤  Works fine for all the servers, but some servlet might use it as

a true path

Page 62: Dynamic content generation

URL rewriting (2)

¤  Added parameter ¤  http://my.server:port/servlet/Rewritten?sessionid=123 ¤  Works on all servers

¤  It fails as a target for forms that use the POST method

¤  Custom change ¤  http://my.server:port/servlet/Rewritten;sessionid=123 ¤  It does not work for those servers that don’t support the change

¤  The session ID is uniquely created for the user, and passed to it by attaching it to the response

Page 63: Dynamic content generation

Session Tracking API

¤  Every user of a site is associated with a java.servlet.http.HttpSession object ¤  This object is used to store and retrieve information about

the user

¤  You can save any set of arbitrary Java objects in a session object

info1

info2

info3

Page 64: Dynamic content generation

Cookies vs. URL rewriting public class SessionDiscover extends HttpServlet {!

!!public void doGet(HttpServletRequest request, HttpServletResponse response)!

!throws IOException, ServletException{ ! !!response.setContentType("text/html");!PrintWriter out = response.getWriter();!

! !!HttpSession session = request.getSession(true);!

! !!out.println("<HTML><HEAD><TITLE> Session Discover </TITLE></HEAD>");!out.println("<BODY>");!out.println("<H2> Session Discover</H2>");!out.println(“<A HREF=" + response.encodeURL(request.getRequestURI()) + "> Refresh </A><BR />"); !

!!out.println("<BR/> SessionID: " + session.getId() + "<BR/>");!out.println("Creation Time: " + new Date(session.getCreationTime()) + "<BR />");!out.println("Last Accessed Time: " + new Date(session.getLastAccessedTime()) + "<BR />");!out.println("Timeout: " + session.getMaxInactiveInterval() + "<BR /><BR />");!

! !!out.println("Using cookies ? " + request.isRequestedSessionIdFromCookie() + "<BR />");!out.println("Using URL Rewriting ? " + request.isRequestedSessionIdFromURL() + "<BR />");!out.println("</BODY></HTML>");!!

! !!}!

}

Encodes the required URL, in case adding the session ID when URL rewriting is enabled

Returns the request URI (we are refreshing the current page!)

Retrieve the session from the request (if it doesn’t exist, it is

created)

Print data about the created session

Specifies whether cookies and URL

rewriting are enabled

Page 65: Dynamic content generation

Using cookies

No session ID in the URL = no URL rewriting

Cookies are enabled = the session ID is stored in the cookies

Page 66: Dynamic content generation

Stored cookie

The cookie reports the URL of the server that required its storage

The value of the cookie reports the session ID

Page 67: Dynamic content generation

Disable cookies

Cookies are disabled = the URL rewriting is active

URL rewriting is active and the session ID is attached to the URL

Page 68: Dynamic content generation

Handling the session

¤  Retrieving the session: getSession(boolean create) on the request

¤  Save an object in the session: setAttribute(name, object) on the session

¤  Retrieve an object from the session: getAttribute(name) on the session

¤  Retrieve the names of all the objects stored in the session: getAttributeNames() on the session

¤  Remove an object from the session: removeAttribute(name) on the session

Page 69: Dynamic content generation

SessionCounter servlet

public class SessionCounter extends HttpServlet {!public void doGet(HttpServletRequest request, HttpServletResponse response) !

! ! !throws ServletException, IOException {!response.setContentType("text/plain");!PrintWriter out = response.getWriter();!

! !!HttpSession session = request.getSession(true);!

! !!Integer count = (Integer)session.getAttribute("session.count");!if (count == null) !

count = new Integer(1);!else!

count = new Integer(1+count.intValue());!session.setAttribute("session.count", count);!

! !!out.println("You have visited this page " + (count.intValue()) + " times.");!out.println("Your session data: ");!Enumeration<String> names = session.getAttributeNames();!while (names.hasMoreElements()) {!

String name = names.nextElement();!!out.println(name + ": " + session.getAttribute(name));!

}!}!

}

Retrieve the current session from the request (create one if necessary)

Read the session attribute named session.count

Store the new counter value in the session

Page 70: Dynamic content generation

Shopping cart application

HTML form •  Select products •  Go to cart

Store cart servlet •  Extract selected products

from the request •  Store the cart in the session

Checkout cart servlet •  Extract selected products

from the session •  Create a report

Page 71: Dynamic content generation

Shopping cart application – Form

<html>!<head><title>Fill shopping cart</title></head>!<body>!

Choose your products:!<form method=POST action="/SlidesExamples/StoreCart">!

<input type="checkbox" name="item" value="chair"/> Chair<br />!<input type="checkbox" name="item" value="table"/> Table<br />!<input type="checkbox" name="item" value="sofa"/> Sofa <br />!<input type="checkbox" name="item" value="desk"/> Desk <br />!<input type="checkbox" name="item" value="painting"/> Painting <br />!<input type="submit" value="See your cart"/>!

</form>!</body>!

</html> All the values that will be selected will be grouped under the parameter name item

Page 72: Dynamic content generation

Shopping cart application – Store cart (1)

public class StoreShoppingCart extends HttpServlet {!!

public void doGet(HttpServletRequest request, HttpServletResponse response)!! !throws ServletException, IOException {!

response.setContentType("text/html");!PrintWriter out = response.getWriter();!! !!

out.println("<html>");!out.println("<head><title>Your shopping cart</title></head>");!out.println("<body>Your items:");!! !!

String[] cartItems = request.getParameterValues("item");!if (cartItems == null)!

out.println("No items were selected.");!else {!

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

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

}!! !!! !

Retrieve the selected products from the request

Page 73: Dynamic content generation

Shopping cart application – Store cart (1)

HttpSession session = request.getSession(true);!session.setAttribute("cartItems", cartItems);!! !!out.println("<form method=POST action=\"/SlidesExamples/checkout\">");!out.println("<input type=\"submit\" value=\"Checkout\">");!out.println("</form></body></html>");!

}!!!

public void doPost(HttpServletRequest request, HttpServletResponse response)!

! ! !throws ServletException, IOException {!doGet(request, response);!

}!!!

}

Store the cart in the session

Go to the next page by using a form

Page 74: Dynamic content generation

Shopping cart application - Checkout

public void doGet(HttpServletRequest request, HttpServletResponse response)!!throws ServletException, IOException {!

response.setContentType("text/html");!PrintWriter out = response.getWriter();!

! !!out.println("<html>");!out.println("<head><title>Checkout</title></head>");!out.println("<body>Your items:");!

! !!HttpSession session = request.getSession();!String[] cartItems = (String[])session.getAttribute("cartItems");!if (cartItems == null)!

!out.println("No items were selected.");!else {!

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

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

}!out.println("</body></html>");!

}!

Retrieve the selected products from the session

Page 75: Dynamic content generation

The session life cycle

¤  A session does not last forever. It expires: ¤  Either automatically ¤  Or after a set time of inactivity (default: 30 min)

¤  You can change the expire time from web.xml; this value will be valid for the entire web application <session-config>!

!<session-timeout>20</session-timeout>!</session-config>!

¤  You can also set this time for a specific instance: session.setMaxInactiveInterval(int secs)!

Page 76: Dynamic content generation

Java Servlets Redirect and Forward

Page 77: Dynamic content generation

Sending requests to other pages

¤  Forward ¤  Performed internally by the application ¤  The browser is completely unaware that it has taken place (i.e.,

the original URL remains intact) ¤  The resulting page repeats the original request with the original

URL

¤  Redirect ¤  The web application instructs the browser to fetch a second URL

(different from the original one) ¤  A browser reload of the second URL does not repeat the original

request ¤  Objects placed in the original request scope are not available

to the second request

Page 78: Dynamic content generation

Redirect or forward?

Redirect Forward

Request1

Request2 = alter(Request1)

Request2

Request1

Request1

Page 79: Dynamic content generation

Redirecting

A new request is sent to the second servlet, thus the request parameters are not visible, i.e., the query string is empty Moreover, although a new attribute was added to the request, it is not visualized in the resulting page (the new request has not attributes)

Page 80: Dynamic content generation

Forwarding

The request parameters are passed to the second servlet, since the same request is used Moreover, the added attribute is visible in the second servlet: the attributes are still visible

Page 81: Dynamic content generation

References

Page 82: Dynamic content generation

References

¤  Java Servlet Programming, Jason Hunter and William Crawford, O’Reilly