Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
CS6320 – Servlet Sessions L. Grewe 1 What is a session? A lasting connection between a user (or client) and a peer, typically a server, usually involving the exchange of many packets between the user's computer and the server Used in applications where need to maintain information between interactions of client and server. • e.g. shopping, chat, etc. 2 Servlet and HttpSession Uses either : cookies if available or URL re-writing. 3 Example – using sessions to support shopping (supported by cookies) request id1 Web browser 1 request Servlet put cookie id1 response id1 response Create Session Web server Here session maintains an ID for the session and this is used to reference a database list of items currently in the user’s shopping cart 4 Session Cookies request id2 Web browser 2 request put cookie id2 response Servlet id2 id1 response Create Session Web server 5 Session Cookies request request Cookie: id1 id1 Web browser 1 Servlet id2 response id1 Web server response Session read/write 6 Session Cookies request request Cookie: id2 id2 Web browser 2 Servlet id2 response id1 Web server response Session read/write 7 sessionId list 8 How do we use HttpSession The session object is represented by the class HttpSession Use the methods getSesssion() or getSession(true) of the doXXX HttpServletRequest object to get the current HttpSession object, or to create one if it doesn’t exist • When a new session is created, the server automatically add a session cookie to the response Use getSession(false) if you do not want to create a new session when no session exists 9 Set attributes associated with a session Session data is accessed in a hash-table fashion: - setAttribute(String name,Object value) - Where is this value stored? - Object getAttribute(String name) More methods: - removeAttribute, getAttributeNames - isNew, invalidate, getId - getCreationTime, getLastAccessedTime - getMaxInactiveInterval, setMaxInactiveInterval 10 Example: A Basic Shopping Cart In the following example a basic shopping cart for an online store is implemented The application consists of two Servlets: - Store.java: the main store site - ShoppingCart.java: handles cart manipulation 11 Online-Store Example Store.java public class Store extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println("<html><head>" + "<link rel=\"stylesheet\" type=\"text/css\"" + " href=\"cartstyle.css\"/></head><body>"); HttpSession session = req.getSession(); if (session.getAttribute("item-list") == null) { out.println("<h1>Hello new visitor!</h1>"); session.setAttribute("item-list", new LinkedList()); } 12 List itemList = (List) session.getAttribute("item-list"); Online-Store Example (cont) out.println("<h2>Your Shopping Cart:</h2><ol>"); for (Iterator it = itemList.iterator(); it.hasNext();) out.println("<li>" + it.next() + "</li>"); out.println("</ol>"); out.println("<form method=\"post\" action=\"cart\">"); out.println("<p>Add item:<input name=\"item\" type=\"text\"/>" + "<input type=\"submit\" value=\"send\"/></p>" + "<p><input type=\"submit\" value=\"empty cart\" " + "name=\"clear\"/></p></form>"); out.println("</body></html>"); } } 13 Store.java Online-Store Example (cont) ShoppingCart.java public class ShoppingCart extends HttpServlet { public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); List items = (List) req.getSession().getAttribute("item-list"); out.println("<html><head><link rel=\"stylesheet\"" + " type=\"text/css\" href=\"cartstyle.css\"/>" + "</head><body>"); 14 Online-Store Example (cont) if (req.getParameter("clear") != null) { items.clear(); out.println("<h2>Your Shopping Cart is Empty!</h2>"); } else { String item = req.getParameter("item"); items.add(item); out.println("<h2>The item <i>" + item + "</i> was added to your cart.</h2>"); } out.println("<h2><a href=\"store\">Return to the store</a></h2>"); out.println("</body></html>"); }} ShoppingCart.java 15 The Session Listener Potentially useful class The session listener reacts to the following events: • A new session has been created • A session is being destroyed To obtain a session listener, implement the interface javax.servlet.http.HttpSessionListener 16 Session-Listener Example @WebListener (cont) public class CartInitializer implements HttpSessionListener { public void sessionCreated(HttpSessionEvent se) { List itemList = new LinkedList(); se.getSession().setAttribute("item-list",itemList); itemList.add("A Free Apple"); } public void sessionDestroyed(HttpSessionEvent se) {} CartInitializer.java } OR if old version Java EE specify in web.xml <listener> <listener-class>CartInitializer</listener-class> </listener> 17