Session Tracking by Kamalakar Dandu

Embed Size (px)

Citation preview

  • 8/2/2019 Session Tracking by Kamalakar Dandu

    1/25

  • 8/2/2019 Session Tracking by Kamalakar Dandu

    2/25

    How Do We Need HTTP State?

    Web applications need to track the users

    across a series of requests:

    -Online shopping (e.g. Order books)

    -Financial portfolio manager-Movie listings

    HTTP does not support directly

    Need a mechanism to maintain state

    about a series of requests from the sameuser ( or originating from the samebrowser) over some period of time

  • 8/2/2019 Session Tracking by Kamalakar Dandu

    3/25

    User Authentication

    Use authenticationto track a user through

    a site:

    The user has to login when visiting the site

    Each request includes the login information such as the user's name

    How to support HTTP Authentication?

    Set up with admin tool (e.g. Tomcat web.xml)

    The server and browser take care of the detail How to get the user's name in a servlet?

    String userName = request.getRemoteUser();

    String[] cartItems =

    getItemsFromCart(userName);

  • 8/2/2019 Session Tracking by Kamalakar Dandu

    4/25

    URL Rewriting

    URLs can be rewritten or encoded to include session

    information

    URL rewriting usually includes a session id

    id can be sent as extra path information:

    http://.../servlet/Rewritten/688

    Works well if no need for extra path info

    id can be sent as an added parameter:

    http://.../servlet/Rewritten?sessionid=688

    Doesn't work with POST, cause name clash

    Id can be sent by a custom change technique:

    http://.../servlet/Rewritten;$sessionid$688

    May not work for all servers

  • 8/2/2019 Session Tracking by Kamalakar Dandu

    5/25

    Hidden Form Fields

    Hidden form fields are another way to support session tracking. Hidden form fields do not display in the browser, but can be sent back to the server by submit. Fields can have identification (session id) or just some

    thing to remember (occupation). Servlet reads the fields using request.getParameter(). ...

    ...

  • 8/2/2019 Session Tracking by Kamalakar Dandu

    6/25

    Using Cookies in Servlets

    Cookie definition: Web server sends a cookie name and value to a browser and later can read them back from the browser

    The process: Servlet sends a cookie with its response to the client . The client saves the cookie The client returns a cookie back with subsequent

    requests (depends on some rules) Typical Uses of Cookies Identifying a user during an e- commerce session. Cookies can save either information or identification

  • 8/2/2019 Session Tracking by Kamalakar Dandu

    7/25

    Cookies

    Used to send information to client whichthe the server uses to identify the client.

    Once set, whenever the user visits thepage, the cookie is sent from thebrowser to the client

    Web browsers support 20 cookies perhost (of at least 4Kb each)

  • 8/2/2019 Session Tracking by Kamalakar Dandu

    8/25

    Cookies (contd)

    Steps to send a cookie

    Instantiate a new cookie (before getWriter)Cookie c1 = new Cookie(BookToBuy, jskd)

    Cookie contains a header and a valueSet any attributessetMaxAge(int), setPath(String), setSecure(),setValue(String), setDomain(String),setComment(String), setVersion()getName(), plus all methods with getxxx() as above

    send cookie: to send cookie add it to the response objectres.addCookie(c1);

    Cookie names can be alphanumeric strings.

    They should not contain special characters like[ ] ( ) = , / ? @ : ; Two cookies can have the same name.

  • 8/2/2019 Session Tracking by Kamalakar Dandu

    9/25

    Cookie Attributes MaxAge: maximum age of cookie in

    seconds before it expires. Specialvalues

    -1 (default) expires when the browser exits

    0 delete the cookie immediately

    Value: specify value of cookie

    Secure: specify whether cookie

    requires secure channel such as SSL

    Path: specify path for a cookie.Represents a subset of URIs which should

    get the cookie

    Cookies are sent to the page that set the cookies and toall pages and directories under that. If

    /servlet/CookieDemo set the cookie, than path is

    /servlet. Hence all pages within/servlet will get the

    cookie. However a page under/cgi-bin will not get this

    cookie. Hence cookies can be shared by many servlets.

  • 8/2/2019 Session Tracking by Kamalakar Dandu

    10/25

    Cookie Attributes(contd)

    Version: specify version of cookie to beused. Versions available 0: Netscape persistent cookies (default

    type, and supported widely)

    1: RFC 2109 cookies Comment: intended to describe thepurpose of cookie (may not besupported by all browsers)

    version 0 cookies do not supportcomments

    Domain: specify servers that should seea cookie

    setDomain(.foo.com)

    Pattern must begin with a dot and must have atleast 2 dots. Pattern matches only one entry

    beyond the initial dot. Hence the above matcheswww.foo.com, but not www.upload.foo.com.

  • 8/2/2019 Session Tracking by Kamalakar Dandu

    11/25

    Cookie (contd)

    Steps to Retrieve a cookie

    Retrieve all cookies from the users

    request

    Cookie[] ac = req.getCookies();

    find the cookie(s) with the name you are

    interested in, and then get the values ofthe cookie

    if (ac[i].getName.equals(BookToBuy))

    String val = ac[i].getValue();

  • 8/2/2019 Session Tracking by Kamalakar Dandu

    12/25

    Demo: Example

    Write a servlet that displays a textfield for a user the first

    time he visits the page. Every subsequent visit he gets a

    screen with welcome message and the number of times he has

    visited it.

    Eg: CookieDemo.java

    Write a servlet that deletes cookies created by your

    application only.

    Eg: CookieDel.java

  • 8/2/2019 Session Tracking by Kamalakar Dandu

    13/25

    HTTPSession Tracking Overview

    The servlet API has a built-in support for session tracking Session objects live on the server Each user has associated an HttpSession objectone

    user/session It operates like a hashtable To get a user's existing or new session object: HttpSession session = request.getSession(true); "true" means the server should create a new session

    object if necessary To store or retrieve an object in the session: Stores values: setAttribute("cartItem", cart); Retrieves values: getAttribute("cartItem");

  • 8/2/2019 Session Tracking by Kamalakar Dandu

    14/25

    Session Tracking API

    getAttribute

    retrieves a previously stored value from a

    session, and null if no value found

    setAttribute

    Stores a value in a session

    removeAttribute

    Removes values associated with name

    String[] session.getAttributeNames

    Returns names of all attributes in the session

    getId

    Returns the unique identifier

  • 8/2/2019 Session Tracking by Kamalakar Dandu

    15/25

    Session Lifecycle API

    Sessions usually timeout after 30 minutes of inactivity A different timeout may be set by server admin public void invalidate() Expires the session and unbinds all objects with it.

    boolean session.isNew() Determines if session is new to client (not page). long session.getCreationTime() Returns time at which session was first created.

    long session.getLastAccessedTime() Returns when the user last accessed the server. getMaxInactiveInterval, setMaxInactiveInterval Gets or sets the amount of time, session should go

  • 8/2/2019 Session Tracking by Kamalakar Dandu

    16/25

    Session Tracking Usage

    When clients at an on- line store add an

    item to their shopping cart, how does the

    server know whats already in the cart? When clients decide to proceed to

    checkout, how can the server determine

    which previously created shopping cart is theirs?

  • 8/2/2019 Session Tracking by Kamalakar Dandu

    17/25

    Obtain a Session

    public class CatalogServlet extends HttpServlet {

    public void doGet (HttpServletRequest request,

    HttpServletResponse response)

    throws ServletException, IOException {

    // Get the user's session and shopping cart

    HttpSession session =request.getSession(true);

    ...

    out = response.getWriter();

    ...

    }

    }

  • 8/2/2019 Session Tracking by Kamalakar Dandu

    18/25

    Storing and Getting Data From aSession

    Example : CatalogServlet.java

    InvalidatetheSession

    Example : ReceiptServlet.java

  • 8/2/2019 Session Tracking by Kamalakar Dandu

    19/25

    Java Servlet 2.3 Lifecycle Event

    New events framework More global control than any one servlet or JSP can provide

    Support event notifications for state changes in ServletContext and HttpSession objects Scope ServletContext: manage state held at a VM

    level for the application - HttpSession: manage state or resourcesassociatedwith a series of requests from the same user

  • 8/2/2019 Session Tracking by Kamalakar Dandu

    20/25

    ServletContext and HttpSession

    Interesting things on the servletcontexts: Manage Startup/shutdown Attribute changes

    Interesting events on HTTP sessions: Creation and invalidation Changes in attributes Migration across distributed containers

    Attribute changes to both objects may occur concurrently No synchronization support in container - Listener classes need to support data integrity

  • 8/2/2019 Session Tracking by Kamalakar Dandu

    21/25

    Listener Registration

    creates an instance of each listener class registers it for event notifications before processing first request by the application

    Registers the listener instances according to the interfaces they implement the order in which they appear in the deployment descriptor web.xml

    Listeners are invoked in the order of theirregistrationduring execution

  • 8/2/2019 Session Tracking by Kamalakar Dandu

    22/25

    Listening Interfaces

    ServletContextListener contextInitialized/Destroyed(ServletContextEvent) ServletContextAttributeListener attributeAdded/Removed/Replaced(

    ServletContextAttributeEvent) HttpSessionListener sessionCreated/Destroyed(HttpSessionEvent) HttpSessionAttributeListener attributedAdded/Removed/Replaced(

    HttpSessionBindingEvent) HttpSessionActivationListener Handles sessions migrate from one server to another sessionWillPassivate(HttpSessionEvent)

    sessionDidActivate(HttpSessionEvent)

  • 8/2/2019 Session Tracking by Kamalakar Dandu

    23/25

    Basic Steps for ImplementingEvent Listeners

    Implement the appropriate interface

    Override the methods needed to respond to

    the events of interest

    Obtain access to the important Web

    application objects

    Servlet context

    Servlet context attribute, its name and value

    Session, session attribute name and value

  • 8/2/2019 Session Tracking by Kamalakar Dandu

    24/25

    Use these objects

    e.g. Servlet context: getInitParameter(),

    setAttribute() and getAttribute()

    Declare the listener

    Configure listener and listener-class inweb.xml or a

    tag library descriptor file(.tld) Provide any needed initialization parameters

    Basic Steps for ImplementingEvent Listeners (contd..)

  • 8/2/2019 Session Tracking by Kamalakar Dandu

    25/25

    Session Listener Example

    Example : SessionCounter.java