SlideShare a Scribd company logo
1 of 82
Download to read offline
Dynamic content generation
Eleonora Ciceri
ciceri@elet.polimi.it
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
HTTP basics
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
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
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
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
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
Java Servlets
Basic concepts
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
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)
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
responseHTTP response
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
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
GenericServlet
¤  This servlet overrides the service() method to handle
requests, taking as inputs:
¤  The request object
¤  The response object
request
response
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
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
Java Servlets
Basic coding using Java Servlet API
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>HelloWorldServlet</TITLE></HEAD>");!
! !out.println("<BODY>");!
! !out.println("Hello, World!");!
! !out.println("</BODY>");!
! !out.println("</HTML>");!
! !out.close();!
!}!
}
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>HelloWorldServlet</TITLE></HEAD>");!
! !out.println("<BODY>");!
! !out.println("Hello, World!");!
! !out.println("</BODY>");!
! !out.println("</HTML>");!
! !out.close();!
!}!
}
Hello World! servlet
HTTP servlet
interface
Packages
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>HelloWorldServlet</TITLE></HEAD>");!
! !out.println("<BODY>");!
! !out.println("Hello, World!");!
! !out.println("</BODY>");!
! !out.println("</HTML>");!
! !out.close();!
!}!
}
Hello World! servlet
Request object
Response object
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>HelloWorldServlet</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
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>HelloWorldServlet</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
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>HelloWorldServlet</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
Hello World! servlet results
Servlet’s path: project path + servlet’s name
Printed content
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)
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
Java Servlets
Input and output
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
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
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
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
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
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
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
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,
! ! ! !HttpServletResponseresponse)!
! !throws ServletException, IOException {!
!doGet(request, response);!
}!
Java Servlets
Instance persistence
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
¤  …
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
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
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 countThread1.print()
Thread2.print()
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
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
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);!
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
Java servlets
Init and context parameters
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
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
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
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
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
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”
Java Servlets
Session tracking
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
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
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
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
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()
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
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
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
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
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
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
Using cookies
No session ID in the URL =
no URL rewriting
Cookies are enabled =
the session ID is stored in
the cookies
Stored cookie
The cookie reports the URL
of the server that required
its storage
The value of the cookie
reports the session ID
Disable cookies
Cookies are disabled =
the URL rewriting is active
URL rewriting is active and
the session ID is attached
to the URL
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
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
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
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
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
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
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
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)!
Java Servlets
Redirect and Forward
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
Redirect or forward?
Redirect Forward
Request1
Request2 =
alter(Request1)
Request2
Request1
Request1
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)
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
References
References
¤  Java Servlet Programming, Jason Hunter and William
Crawford, O’Reilly

More Related Content

What's hot (20)

Tcpip services and applications
Tcpip services and applicationsTcpip services and applications
Tcpip services and applications
 
Intro to web services
Intro to web servicesIntro to web services
Intro to web services
 
ASP.NET Basics
ASP.NET Basics ASP.NET Basics
ASP.NET Basics
 
Asynchronous JavaScript & XML (AJAX)
Asynchronous JavaScript & XML (AJAX)Asynchronous JavaScript & XML (AJAX)
Asynchronous JavaScript & XML (AJAX)
 
Introduction to ASP.NET
Introduction to ASP.NETIntroduction to ASP.NET
Introduction to ASP.NET
 
Ajax
AjaxAjax
Ajax
 
Ajax presentation
Ajax presentationAjax presentation
Ajax presentation
 
Web design - How the Web works?
Web design - How the Web works?Web design - How the Web works?
Web design - How the Web works?
 
Jsp ppt
Jsp pptJsp ppt
Jsp ppt
 
Html5-Web-Storage
Html5-Web-StorageHtml5-Web-Storage
Html5-Web-Storage
 
Ajax
AjaxAjax
Ajax
 
Html5 for mobiles
Html5 for mobilesHtml5 for mobiles
Html5 for mobiles
 
Ajax and Jquery
Ajax and JqueryAjax and Jquery
Ajax and Jquery
 
Local Storage for Web Applications
Local Storage for Web ApplicationsLocal Storage for Web Applications
Local Storage for Web Applications
 
REST & RESTful Web Services
REST & RESTful Web ServicesREST & RESTful Web Services
REST & RESTful Web Services
 
Asp.net basic
Asp.net basicAsp.net basic
Asp.net basic
 
html5.ppt
html5.ppthtml5.ppt
html5.ppt
 
Introduction to Java
Introduction to Java Introduction to Java
Introduction to Java
 
Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
 
HTTP Request and Response Structure
HTTP Request and Response StructureHTTP Request and Response Structure
HTTP Request and Response Structure
 

Similar to Dynamic content generation

Similar to Dynamic content generation (20)

Java Servlets.pdf
Java Servlets.pdfJava Servlets.pdf
Java Servlets.pdf
 
Java web application development
Java web application developmentJava web application development
Java web application development
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Servlet and servlet life cycle
Servlet and servlet life cycleServlet and servlet life cycle
Servlet and servlet life cycle
 
Advance Java Topics (J2EE)
Advance Java Topics (J2EE)Advance Java Topics (J2EE)
Advance Java Topics (J2EE)
 
JAVA Servlets
JAVA ServletsJAVA Servlets
JAVA Servlets
 
BITM3730Week12.pptx
BITM3730Week12.pptxBITM3730Week12.pptx
BITM3730Week12.pptx
 
Servlet.ppt
Servlet.pptServlet.ppt
Servlet.ppt
 
Servlet.ppt
Servlet.pptServlet.ppt
Servlet.ppt
 
Servlet1.ppt
Servlet1.pptServlet1.ppt
Servlet1.ppt
 
Servlets
ServletsServlets
Servlets
 
AJppt.pptx
AJppt.pptxAJppt.pptx
AJppt.pptx
 
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B KuteJava Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
 
Servlet
Servlet Servlet
Servlet
 
1 java servlets and jsp
1   java servlets and jsp1   java servlets and jsp
1 java servlets and jsp
 
Servlet life cycle
Servlet life cycleServlet life cycle
Servlet life cycle
 
servlet_lifecycle.pdf
servlet_lifecycle.pdfservlet_lifecycle.pdf
servlet_lifecycle.pdf
 
Lecture 2: Servlets
Lecture 2:  ServletsLecture 2:  Servlets
Lecture 2: Servlets
 
Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
 
Servlets intro
Servlets introServlets intro
Servlets intro
 

More from Eleonora Ciceri

DDD - 5 - Domain Driven Design_ Repositories.pdf
DDD - 5 - Domain Driven Design_ Repositories.pdfDDD - 5 - Domain Driven Design_ Repositories.pdf
DDD - 5 - Domain Driven Design_ Repositories.pdfEleonora Ciceri
 
DDD - 4 - Domain Driven Design_ Architectural patterns.pdf
DDD - 4 - Domain Driven Design_ Architectural patterns.pdfDDD - 4 - Domain Driven Design_ Architectural patterns.pdf
DDD - 4 - Domain Driven Design_ Architectural patterns.pdfEleonora Ciceri
 
DDD - 3 - Domain Driven Design: Event sourcing.pdf
DDD - 3 - Domain Driven Design: Event sourcing.pdfDDD - 3 - Domain Driven Design: Event sourcing.pdf
DDD - 3 - Domain Driven Design: Event sourcing.pdfEleonora Ciceri
 
DDD - 2 - Domain Driven Design: Tactical design.pdf
DDD - 2 - Domain Driven Design: Tactical design.pdfDDD - 2 - Domain Driven Design: Tactical design.pdf
DDD - 2 - Domain Driven Design: Tactical design.pdfEleonora Ciceri
 
DDD - 1 - A gentle introduction to Domain Driven Design.pdf
DDD - 1 - A gentle introduction to Domain Driven Design.pdfDDD - 1 - A gentle introduction to Domain Driven Design.pdf
DDD - 1 - A gentle introduction to Domain Driven Design.pdfEleonora Ciceri
 
Artificial Intelligence: an introduction.pdf
Artificial Intelligence: an introduction.pdfArtificial Intelligence: an introduction.pdf
Artificial Intelligence: an introduction.pdfEleonora Ciceri
 
Linked lists - Exercises
Linked lists - ExercisesLinked lists - Exercises
Linked lists - ExercisesEleonora Ciceri
 
Multimedia Information Retrieval and User Behavior
Multimedia Information Retrieval and User BehaviorMultimedia Information Retrieval and User Behavior
Multimedia Information Retrieval and User BehaviorEleonora Ciceri
 
The CrowdSearch framework
The CrowdSearch frameworkThe CrowdSearch framework
The CrowdSearch frameworkEleonora Ciceri
 

More from Eleonora Ciceri (17)

DDD - 5 - Domain Driven Design_ Repositories.pdf
DDD - 5 - Domain Driven Design_ Repositories.pdfDDD - 5 - Domain Driven Design_ Repositories.pdf
DDD - 5 - Domain Driven Design_ Repositories.pdf
 
DDD - 4 - Domain Driven Design_ Architectural patterns.pdf
DDD - 4 - Domain Driven Design_ Architectural patterns.pdfDDD - 4 - Domain Driven Design_ Architectural patterns.pdf
DDD - 4 - Domain Driven Design_ Architectural patterns.pdf
 
DDD - 3 - Domain Driven Design: Event sourcing.pdf
DDD - 3 - Domain Driven Design: Event sourcing.pdfDDD - 3 - Domain Driven Design: Event sourcing.pdf
DDD - 3 - Domain Driven Design: Event sourcing.pdf
 
DDD - 2 - Domain Driven Design: Tactical design.pdf
DDD - 2 - Domain Driven Design: Tactical design.pdfDDD - 2 - Domain Driven Design: Tactical design.pdf
DDD - 2 - Domain Driven Design: Tactical design.pdf
 
DDD - 1 - A gentle introduction to Domain Driven Design.pdf
DDD - 1 - A gentle introduction to Domain Driven Design.pdfDDD - 1 - A gentle introduction to Domain Driven Design.pdf
DDD - 1 - A gentle introduction to Domain Driven Design.pdf
 
Artificial Intelligence: an introduction.pdf
Artificial Intelligence: an introduction.pdfArtificial Intelligence: an introduction.pdf
Artificial Intelligence: an introduction.pdf
 
Sorting algorithms
Sorting algorithmsSorting algorithms
Sorting algorithms
 
Trees
TreesTrees
Trees
 
Linked lists - Exercises
Linked lists - ExercisesLinked lists - Exercises
Linked lists - Exercises
 
Doubly Linked Lists
Doubly Linked ListsDoubly Linked Lists
Doubly Linked Lists
 
Linked lists
Linked listsLinked lists
Linked lists
 
AJAX - An introduction
AJAX - An introductionAJAX - An introduction
AJAX - An introduction
 
JDBC in Servlets
JDBC in ServletsJDBC in Servlets
JDBC in Servlets
 
Client side scripting
Client side scriptingClient side scripting
Client side scripting
 
HTML5 - An introduction
HTML5 - An introductionHTML5 - An introduction
HTML5 - An introduction
 
Multimedia Information Retrieval and User Behavior
Multimedia Information Retrieval and User BehaviorMultimedia Information Retrieval and User Behavior
Multimedia Information Retrieval and User Behavior
 
The CrowdSearch framework
The CrowdSearch frameworkThe CrowdSearch framework
The CrowdSearch framework
 

Recently uploaded

2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 

Recently uploaded (20)

2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 

Dynamic content generation

  • 1. Dynamic content generation Eleonora Ciceri ciceri@elet.polimi.it
  • 2. 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
  • 4. 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
  • 5. 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
  • 6. 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
  • 7. 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
  • 8. 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
  • 10. 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
  • 11. 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)
  • 12. 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 responseHTTP response
  • 13. 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
  • 14. 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
  • 15. GenericServlet ¤  This servlet overrides the service() method to handle requests, taking as inputs: ¤  The request object ¤  The response object request response
  • 16. 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
  • 17. 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
  • 18. Java Servlets Basic coding using Java Servlet API
  • 19. 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>HelloWorldServlet</TITLE></HEAD>");! ! !out.println("<BODY>");! ! !out.println("Hello, World!");! ! !out.println("</BODY>");! ! !out.println("</HTML>");! ! !out.close();! !}! }
  • 20. 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>HelloWorldServlet</TITLE></HEAD>");! ! !out.println("<BODY>");! ! !out.println("Hello, World!");! ! !out.println("</BODY>");! ! !out.println("</HTML>");! ! !out.close();! !}! } Hello World! servlet HTTP servlet interface Packages
  • 21. 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>HelloWorldServlet</TITLE></HEAD>");! ! !out.println("<BODY>");! ! !out.println("Hello, World!");! ! !out.println("</BODY>");! ! !out.println("</HTML>");! ! !out.close();! !}! } Hello World! servlet Request object Response object
  • 22. 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>HelloWorldServlet</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
  • 23. 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>HelloWorldServlet</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
  • 24. 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>HelloWorldServlet</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
  • 25. Hello World! servlet results Servlet’s path: project path + servlet’s name Printed content
  • 26. 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)
  • 27. 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
  • 29. 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
  • 30. 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
  • 31. 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
  • 32. 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
  • 33. 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
  • 34. 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
  • 35. 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
  • 36. 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, ! ! ! !HttpServletResponseresponse)! ! !throws ServletException, IOException {! !doGet(request, response);! }!
  • 38. 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 ¤  …
  • 39. 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
  • 40. 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
  • 41. 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 countThread1.print() Thread2.print()
  • 42. 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
  • 43. 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
  • 44. 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);!
  • 45. 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
  • 46. Java servlets Init and context parameters
  • 47. 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
  • 48. 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
  • 49. 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
  • 50. 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
  • 51. 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
  • 52. 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”
  • 54. 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
  • 55. 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
  • 56. 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
  • 57. 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
  • 58. 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()
  • 59. 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
  • 60. 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
  • 61. 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
  • 62. 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
  • 63. 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
  • 64. 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
  • 65. Using cookies No session ID in the URL = no URL rewriting Cookies are enabled = the session ID is stored in the cookies
  • 66. Stored cookie The cookie reports the URL of the server that required its storage The value of the cookie reports the session ID
  • 67. Disable cookies Cookies are disabled = the URL rewriting is active URL rewriting is active and the session ID is attached to the URL
  • 68. 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
  • 69. 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
  • 70. 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
  • 71. 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
  • 72. 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
  • 73. 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
  • 74. 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
  • 75. 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)!
  • 77. 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
  • 78. Redirect or forward? Redirect Forward Request1 Request2 = alter(Request1) Request2 Request1 Request1
  • 79. 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)
  • 80. 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
  • 82. References ¤  Java Servlet Programming, Jason Hunter and William Crawford, O’Reilly