Anda di halaman 1dari 37

Session Handling

Contents

1 State
2 Ways to achieve session tracking
3 URL Rewriting
4 Disadvantages
5 Hidden Form Fields
6 Cookie
7 javax.servlet.http.Cookie
8 Try
9 Advantage
10 Servlet way of maintaining session: HttpSession
Contents

11 Methods to create HttpSession


12 Session and cookies working together
13 Storing values in the session
14 Retrieving values from the session
15 Removing attributes from the session
16 Methods in HttpSession
17 Shopping Cart
18 Destroying session
19 Timeout
20 Cookies disabled
Contents

21 Encode URL
22 Summary of types of attributes in the application that we have seen so far
Know
• Why session tracking is necessary
• Ways to achieve session tracking
• How to track sessions with servlets
Be able to
• Write implement session handlings in servlets
State
• Some applications require us to maintain
information particular to a user that spans more
than one request-response cycle.
• Maintaining user information/state between multiple
request-response cycle is termed as session
tracking.
– 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 maintain
the cart information as the customer moves from one
page to another.
Ways to achieve session tracking

• URL rewriting
• Hidden form fields
• Cookies
URL Rewriting
…..
Name www.ab.com/myservlet?name=x
….. Server

Submit

Links
www.ab.com/shop?name=x
2. Shop with us
Server
3. View products

Keep resending the request parameters as query


string along with all the URLs
Disadvantages

• URL rewriting requires all the pages in the


application to be dynamically generated. Hence
it cannot be enforced for a static html page.
Hidden Form Fields
• In this approach a hidden field is embedded with
the form for all the pages.
• <INPUT TYPE=“hidden” NAME=“uid”
VALUE=“123”>
• This approach also has the same disadvantage
as URL rewriting.
• Also every page must have a form.
Cookie
• A small piece of textual information sent by the
server to the client, stored on the client’s machine,
and returned by the client’s 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.
javax.servlet.http.Cookie
• Set-Cookie:NAME=VALUE;Comment=COMMENT;
Domain=DOMAINNAME;Max-Age=SECONDS;
Path=PATH;secure
Response header cookie format
• example:Set-Cookie:userid=anita;Max-
Age=60;Domain=“.myser.com”;Path=“/”

Response header cookie example

//Setting cookie
Cookie c=new Cookie(“userid”, “ram”);
c.setMaxAge(60);
c.setDomain(“myser.com”);
c.setPath(“/”); Cookie available for all
response.addCookie(c); the paths entire web site
//Getting cookie
Cookie[] cookies=request.getCookies();
for(int i=0; i<cookies.length; i++)
{
String name=cookies[i].getName();
String value=cookies[i].getValue();
}
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 and
password 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.
Advantage
• Cookies are not mixed up with the HTML
content, request or response bodies. The server
can transparently set the cookie in the response
header and extract from the request header.

Bad news is the client can disable cookies.


Servlet way of maintaining
session: HttpSession
• A very simple solution to session handling –
HttpSession.
• Java servlet API has an interface called
HttpSession which helps us in session
tracking.
– The web container uses either cookies or URL
rewriting for establishing session.
Methods to create HttpSession
• HttpServletRequest has following
methods to create HttpSession:
– HttpSession getSession(boolean
create)
– HttpSession getSession()
Methods to create HttpSession
HttpSession getSession(boolean
create)
– If create is true it functions in the same way
as the function given below.
– If create is false, if there is no session
associated with the request, this method
returns null else returns the session
associated with this request.
Methods to create HttpSession

HttpSession getSession()
– Returns the current session associated with
this request, or if the request does not have
a session, creates one.
Session and cookies working
together
1.Submits client information

3. Sets Session and returns response Application


Client (Set-Cookie: JSESSIONID=1A5686;)
Server
4.Sends another request
(Cookie attached with the request)

2.Generates unique JSESSIONID and


stores the object against the sessionID
JSESSIONID Object …

…. … …
5. Retrieves the object
associated with
123457 XYZ …
the JSESSIONID
1A5686 ClientInfo …
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”)
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”);
Removing attributes from the
session
• To remove attributes from the session object
• void removeAttribute(String name)
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
Shopping Cart
• Shopping cart is the best example to
demonstrate session.
• We will see a minimum application that
demonstrates that implements a shopping cart.
• User can select items from the Books page and
the CD page and add to cart.
• User can view the cart content at any point of
time.
• User can also invalidate the session.
index.html
ShowServlet
book.html

AddToCartServlet

music.html

ShowServlet
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) throws
ServletException, IOException {
PrintWriter out = response.getWriter();
try{
String booktitle=
request.getParameter("name");
String[] music=
request.getParameterValues("music");
String[] book=
request.getParameterValues("book");
HttpSession session= request.getSession();
ArrayList
cart=(ArrayList)session.getAttribute("cart");
if(cart==null)
cart= new ArrayList(); Create a new session if a
session does not exist
if(music!=null)
for(int i=0;i<music.length;i++)
cart.add(music[i]);

if(book!=null) Add attributes in the session


for(int i=0;i<book.length;i++)
cart.add(book[i]);
session.setAttribute("cart",cart);
out.println("Added to the cart<br>");
out.println("<a href=show.do?flag=n>Show
Cart</a><br>");
‘n’ indicates no session invalidation
out.println("<a href=show.do?flag=y>Show and
Invalidate Session</a><br>");
Session invalidation indicator
out.println("<a
href=book.html>Books</a><br>");
out.println("<a
href=music.html>Musics</a><br></body></html>")
;
}catch(Exception e){
out.println("<html><body><font color=red>Some
invalid operation caused an exception to be
raised</font>");
out.println("<p> Exception generated
:"+e.toString()+"</p></body></html>");}
finally{
out.close();
}}
}
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{ Determines if the session
has to be invalidated
String flag=request.getParameter("flag");
Get the existing session
out.println("<html><body><h1<br>");
HttpSession session= request.getSession(false);
ArrayList
cart=(ArrayList)session.getAttribute("cart");
for(int i=1;i<=cart.size();i++)
out.println(i+". "+ cart.get(i-1)+"<br>");

if(flag.equals("y"))
session.invalidate();

out.println("<a href=index.html>Home</a>");
out.println("</body></html>");
}catch(Exception e){
out.println("<html><body><font color=red>Some
invalid operation caused an exception to be
raised</font>");
out.println("<p> Exception generated
:"+e.toString()+"</p></body></html>");}
finally{
out.close();}}}
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, accessing
session attributes causes
IllegalStateException.
Timeout
• Two ways to set timeout period
• Through the method of HttpSession
•Object setMaxInactiveInterval(int
interval)
• Through DD
<session-config>
<session-timeout>
30
<session-timeout>
</session-config>
Timeout interval given in minutes.
Cookies disabled
• Some browsers may have cookies disabled.
• If cookie is disabled, the session code that we
have 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 when
cookies do not work.
Encode URL
• encodeURL() method of HttpResponse class
must be used on all the URLs so that the URL
rewriting mechanism works!
• This in turn also means that all the pages must
be dynamically generated.
• out.println("<a href=“+
response.encodeURL(“show.do”)+”>Show
Cart</a><br>");
• Note that URL rewriting is done in vendor-specific
way. For instance Tomcat uses a
semicolon(‘;’) to append the extra info to the
URL.
show.do;jsessionid=00WV14552
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

Anda mungkin juga menyukai