Professional Documents
Culture Documents
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
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); =,/?@:;
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
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(); ... } }
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)
Example : SessionCounter.java