You are on page 1of 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 same user ( or originating from the same browser) over some period of time

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);

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

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(). <FORM ACTION="/servlet/ShowParameters" METHOD="POST">... <INPUT TYPE="HIDDEN" NAME="OCCUPATION" VALUE="ENGINEER"> <INPUT TYPE="HIDDEN" NAME="SESSIONID" VALUE="194043"> ... </FORM>

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

Cookies
Used to send information to client which the the server uses to identify the client. Once set, whenever the user visits the page, the cookie is sent from the browser to the client Web browsers support 20 cookies per host (of at least 4Kb each)

Cookies (contd)
Steps to send a cookie Instantiate a new cookie (before getWriter)
Cookie c1 = new Cookie(BookToBuy, jskd) Set Cookie contains a header and a value any attributes setMaxAge(int), setPath(String), setSecure(), setValue(String), setDomain(String), Cookie names can be alphanumeric strings. setComment(String), setVersion() They getName(), plus all methods with getxxx() as above should not contain special characters like send cookie: to send cookie add it to the response object [ ] ( )res.addCookie(c1); =,/?@:;

Two cookies can have the same name.

Cookie Attributes
MaxAge: maximum age of cookie in seconds before it expires. Special values
-1 (default) expires when the browser exits Cookies are sent to the page that set the cookies and to 0 delete the cookie immediately all pages and directories under that. If Value: specify value of cookie /servlet/CookieDemo set the cookie, than path is Secure: all pages within /servlet will /servlet. Hencespecify whether cookie get the requires secure under /cgi-bin will not get cookie. However a pagechannel such as SSL this cookie. Hence cookies can forshared by many servlets. Path: specify path be a cookie. Represents a subset of URIs which should get the cookie

Cookie Attributes(contd)
Version: specify version of cookie to be used. Versions available
0: Netscape persistent cookies (default type, and supported widely) 1: RFC 2109 cookies

Comment: intended to describe the Pattern must begin with a dot and must have at purpose of cookie (may not be least 2 dots. Pattern browsers) one entry supported by all matches only
Domain: specify servers that should see a cookie
setDomain(.foo.com)

beyond the initial dot. do not support version 0 cookies Hence the above matches www.foo.com, but not www.upload.foo.com. comments

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 of the cookie
if (ac[i].getName.equals(BookToBuy)) String val = ac[i].getValue();

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

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");

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

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

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?

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(); ... } }

Storing and Getting Data From a Session


Example : CatalogServlet.java

Invalidate the Session


Example : ReceiptServlet.java

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 resources associated with a series of requests from the same user

ServletContext and HttpSession


Interesting things on the servlet contexts: 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

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 their registration during execution

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)

Basic Steps for Implementing Event 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

Basic Steps for Implementing Event Listeners (contd..)


Use these objects e.g. Servlet context: getInitParameter(), setAttribute() and getAttribute() Declare the listener Configure listener and listener-class in web.xml or a tag library descriptor file(.tld) Provide any needed initialization parameters

Session Listener Example

Example : SessionCounter.java

You might also like