4 session handling
TRANSCRIPT
-
8/14/2019 4 Session Handling
1/37
Session Handling
-
8/14/2019 4 Session Handling
2/37
Servlet way of maintaining session: HttpSession10
Advantage9
Try8
javax.servlet.http.Cookie7
Cookie6
Hidden Form Fields5
Disadvantages4
URL Rewriting3
Ways to achieve session tracking2
State1
Contents
-
8/14/2019 4 Session Handling
3/37
Cookies disabled20
Timeout19
Destroying session18
Shopping Cart17
Methods in HttpSession16
Removing attributes from the session15
Retrieving values from the session14Storing values in the session13
Session and cookies working together12
Methods to create HttpSession11
Contents
-
8/14/2019 4 Session Handling
4/37
Summary of types of attributes in the application that we have seen so far22
Encode URL21
Contents
-
8/14/2019 4 Session Handling
5/37
Know
Why session tracking is necessary
Ways to achieve session tracking
How to track sessions with servlets
-
8/14/2019 4 Session Handling
6/37
Be able to
Write implement session handlings in servlets
-
8/14/2019 4 Session Handling
7/37
State
Some applications require us to maintaininformation particular to a user that spans more
than one request-response cycle.
Maintaining user information/state between multiple
request-response cycle is termed as sessiontracking.
In an on-line shop, a customer will want add items into
the shopping cart while browsing through several pages
of catalogue. Here we require a mechanism to maintainthe cart information as the customer moves from one
page to another.
-
8/14/2019 4 Session Handling
8/37
Ways to achieve session tracking
URL rewriting
Hidden form fields
Cookies
-
8/14/2019 4 Session Handling
9/37
URL Rewriting
Server
Name
..
..
Submit
www.ab.com/myservlet?name=x
Server
Links
2. Shop with us
3. View products
www.ab.com/shop?name=x
Keep resending the request parameters as query
string along with all the URLs
-
8/14/2019 4 Session Handling
10/37
Disadvantages
URL rewriting requires all the pages in the
application to be dynamically generated. Hence
it cannot be enforced for a static html page.
-
8/14/2019 4 Session Handling
11/37
Hidden Form Fields In this approach a hidden field is embedded with
the form for all the pages.
This approach also has the same disadvantage
as URL rewriting.
Also every page must have a form.
-
8/14/2019 4 Session Handling
12/37
Cookie
A small piece of textual information sent by theserver to the client, stored on the clients machine,
and returned by the clients machine with each
request made to the server.
Web server sends cookies by sending the Set-Cookie response header.
Cookies maintain information between more than
one browser session.
-
8/14/2019 4 Session Handling
13/37
javax.servlet.http.Cookie Set-Cookie:NAME=VALUE;Comment=COMMENT;Domain=DOMAINNAME;Max-Age=SECONDS;Path=PATH;secure
example:Set-Cookie:userid=anita;Max-Age=60;Domain=.myser.com;Path=/
//Setting cookie
Cookie c=new Cookie(userid, ram);
c.setMaxAge(60);
c.setDomain(myser.com);
c.setPath(/);
response.addCookie(c);
Response header cookie format
Response header cookie example
Cookie available for all
the paths entire web site
-
8/14/2019 4 Session Handling
14/37
//Getting cookie
Cookie[] cookies=request.getCookies();
for(int i=0; i
-
8/14/2019 4 Session Handling
15/37
Try
Write a servlet which displays login and
password with the values of login and password
set if the cookies are set.
If cookies are not set, then the login andpassword entered by the user are set as cookies
so that when user requests for this page next
time the login and password are automatically
set.
-
8/14/2019 4 Session Handling
16/37
Advantage Cookies are not mixed up with the HTML
content, request or response bodies. The servercan transparently set the cookie in the responseheader and extract from the request header.
Bad news is the client can disable cookies.
-
8/14/2019 4 Session Handling
17/37
Servlet way of maintaining
session: HttpSession
A very simple solution to session handling
HttpSession.
Java servlet API has an interface calledHttpSession which helps us in session
tracking.
The web container uses either cookies or URL
rewriting for establishing session.
-
8/14/2019 4 Session Handling
18/37
Methods to create HttpSession
HttpServletRequest has followingmethods to create HttpSession:
HttpSession getSession(booleancreate)
HttpSession getSession()
-
8/14/2019 4 Session Handling
19/37
-
8/14/2019 4 Session Handling
20/37
Methods to create HttpSession
HttpSession getSession()
Returns the current session associated withthis request, or if the request does not havea session, creates one.
-
8/14/2019 4 Session Handling
21/37
Session and cookies working
together
ClientApplication
Server
1.Submits client information
JSESSIONID Object
.
123457 XYZ
1A5686ClientInfo
3. Sets Session and returns response(Set-Cookie: JSESSIONID=1A5686;)
4.Sends another request(Cookie attached with the request)
2.Generates unique JSESSIONID andstores the object against the sessionID
5. Retrieves the objectassociated with
the JSESSIONID
-
8/14/2019 4 Session Handling
22/37
Storing values in the session
Values can be stored in the session object using
void setAttribute(String name, Object
attribute)
Example: session.setAttribute(uname,scott)
-
8/14/2019 4 Session Handling
23/37
Retrieving values from the session
Values can be retrieved from the session object using
Object getAttribute(String name)
Example: String
o=(String)session.getAttribute(uname);
-
8/14/2019 4 Session Handling
24/37
Removing attributes from the
session
To remove attributes from the session objectvoid removeAttribute(String name)
-
8/14/2019 4 Session Handling
25/37
Methods in HttpSession
Object getAttribute(String name)
void setAttribute(String name, Object
attribute) void removeAttribute(String name)
String getId()
void invalidate()
boolean isNew()
Object can be stored by associating it with a name in the
session thus forming a name-value pair
-
8/14/2019 4 Session Handling
26/37
Shopping Cart
Shopping cart is the best example todemonstrate session.
We will see a minimum application that
demonstrates that implements a shopping cart. User can select items from the Books page andthe CD page and add to cart.
User can view the cart content at any point of
time. User can also invalidate the session.
-
8/14/2019 4 Session Handling
27/37
index.html
book.html
music.html
AddToCartServlet
ShowServlet
ShowServlet
-
8/14/2019 4 Session Handling
28/37
import javax.servlet.http.*;
import javax.servlet.*;
import java.util.ArrayList;
import java.io.*;
public class AddToCartServlet extends
HttpServlet {
public void doPost(HttpServletRequest
request,HttpServletResponse response) throwsServletException, IOException {
PrintWriter out = response.getWriter();
try{
String booktitle=request.getParameter("name");
String[] music=
request.getParameterValues("music");
String[] book=
request.getParameterValues("book");
-
8/14/2019 4 Session Handling
29/37
HttpSession session= request.getSession();
ArrayList
cart=(ArrayList)session.getAttribute("cart");
if(cart==null)
cart= new ArrayList();
if(music!=null)
for(int i=0;i
-
8/14/2019 4 Session Handling
30/37
out.println("Show and
Invalidate Session
");out.println("Books
");out.println("Musics
");
}catch(Exception e){out.println("Some
invalid operation caused an exception to be
raised");
out.println("
Exception generated
:"+e.toString()+"
");}finally{
out.close();
}}
}
Session invalidation indicator
i t j l t htt *
-
8/14/2019 4 Session Handling
31/37
import javax.servlet.http.*;
import javax.servlet.*;
import java.util.ArrayList;
import java.io.*;
public class ShowServlet extends HttpServlet {
public void doGet(HttpServletRequest
request,HttpServletResponse response) throws
ServletException, IOException {
PrintWriter out = response.getWriter();
try{
String flag=request.getParameter("flag");
out.println("
-
8/14/2019 4 Session Handling
32/37
ArrayList
cart=(ArrayList)session.getAttribute("cart");
for(int i=1;i
-
8/14/2019 4 Session Handling
33/37
Destroying session Session gets destroyed in one of the following
ways:
On calling invalidate()
When client does not respond with-in the time-
out period When application crashes
When application is no longer available
After session has become invalid, accessingsession attributes causes
IllegalStateException.
Ti t
-
8/14/2019 4 Session Handling
34/37
Timeout Two ways to set timeout period
Through the method ofHttpSessionObject setMaxInactiveInterval(int
interval)
Through DD
30
Timeout interval given in minutes.
-
8/14/2019 4 Session Handling
35/37
Cookies disabled
Some browsers may have cookies disabled.
If cookie is disabled, the session code that wehave written so far will not work!
To make it work we need to do an extra bit. On doing this extra bit, application server
employs the URL rewriting mechanism whencookies do not work.
-
8/14/2019 4 Session Handling
36/37
Encode URL encodeURL() method ofHttpResponse class
must be used on all the URLs so that the URLrewriting mechanism works! This in turn also means that all the pages must
be dynamically generated.
out.println("ShowCart
");Note that URL rewriting is done in vendor-specificway. For instance Tomcat uses a
semicolon(;) to append the extra info to theURL.
show.do;jsessionid=00WV14552
-
8/14/2019 4 Session Handling
37/37
Summary of types of attributes in the
application that we have seen so far Attributes stored with ServletContext
Available to the entire web application
Attributes stored with ServletConfig Available only to the particular servlet
Attributes stored with HttpSession
Available with respect to the user Attributes stored with HttpServletRequest
Available with respect to particular request