HttpSession: Management of Application Data - PowerPoint PPT Presentation

keely-morrison
httpsession management of application data n.
Skip this Video
Loading SlideShow in 5 Seconds..
HttpSession: Management of Application Data PowerPoint Presentation
Download Presentation
HttpSession: Management of Application Data

play fullscreen
1 / 27
Download Presentation
HttpSession: Management of Application Data
111 Views
Download Presentation

HttpSession: Management of Application Data

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

  1. HttpSession: Management of Application Data 4.1.0.3

  2. Unit objectives After completing this unit, you should be able to: • Discuss the task of managing client application data • Session Management • Describe the use of HttpSession to maintain a user session • Describe how object sharing is implemented in the servlet environment • Describe the various ways to manage application state

  3. Session Management (1 of 2) • Sessions provide a way to identify a user across more than one page request or visit to a Web site and to store information about that user • Web applications must manage state information: • Current customer, shopping cart, and so forth • Application involves several Servlets • Servlets need to be stateless • Multiple implementation technologies including: • HttpSession • HTTP Cookies • HTML Hidden Field • URL Rewriting

  4. Session Management (2 of 2) • The HttpSession interface, part of the Servlet API, provides an interface for managing application state on the server • In applications that are marked as distributable, the session data objects placed into the HttpSession object must be serializable (they must implement the Serializable interface) • WebSphere's HttpSession implementation allows session data to be placed in a shared database or replicated between servers and makes clustering of servers simpler and more robust • A session: • Represents a client-server HTTP connection • Lifetime spans multiple servlets and page requests • Is identified within requests via a Session identifier

  5. Session Usage • Servlet asks to bind to the Session object representing the current session • request.getSession(boolean create) • Method returns the current HttpSession, if it exists • If create is true (or no parameter is specified) AND no current Session exists, a newly created session is returned • The session is unavailable when: • The client browser is closed • The session is explicitly invalidated • The session times out

  6. HttpSession Data Store • HttpSessions store application-specific information • Stored as <"key", object> pairs • void setAttribute(String, Object) • Object getAttribute(String)

  7. Sessions at Run Time - Server • HttpSession objects are managed by the web container • Registered by ID • ID must be delivered to client initially and presented back to server on subsequent requests Application Server Session Table ID value MKA42O... SessionR1 ... ... YM4YLEI... SessionA3 SessionA3 key value "customer" aCustomer "name" "Bob"

  8. Browser Cookie List cookie name value domain "JSESSIONID" YM4YLEI... .ibm.com Sessions at Run Time - Client • Preferred (default) delivery vehicle for session ID is transient Cookie • Alternative URL rewriting supported by HttpServletResponse • No automatic support in JSP pages • Requires ad hoc support for client-side script generated URLs

  9. Sessions at Run Time Browser Application Server Session Table ID value MKA42O... SessionR1 ... ... Cookie List YM4YLEI... SessionA3 cookie name value domain "JSESSIONID" YM4YLEI... .ibm.com SessionA3 key value "customer" aCustomer "name" "Bob"

  10. Session Invalidation • Release HttpSession objects when finished. • An Application Server can only maintain a certain number of HttpSession objects in memory • Sessions can be invalidated either programmatically or through a timeout • session.invalidate • Removes all values from the session • The Session timeout (inactive interval) can be set for the application server as a whole • The default timeout is 30 minutes • Also session.setMaxInactiveInterval(int) can provide session-specific timeout value

  11. Session Invalidation Example import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; publicclass ApplicationLogoutServlet extends HttpServlet { publicvoid doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { HttpSession mySession = req.getSession(false); // Invalidate session if (mySession != null) { mySession.invalidate(); } // Perform additional application logoff processing // and send output response to browser here } }

  12. Session Examples • You follow a simple e-commerce example using the Session API to run an online bookstore • There are two Servlets: • BookChoiceServlet • Allows the user to select choices • Can browse without purchasing • CreditInformationServlet • Takes credit card information • Confirms and processes the order

  13. Bookstore Domain Classes 1 0..* Customer Order name : String creditCardNumber : String customer 1 creditCardExpiration : String 1 lineItems 1 0..* Address SaleLineItem zip : String price : double city : String itemName : String state : String streetAddress : String

  14. Book Choice Servlet (1 of 2) public void doPost(req, resp) { resp.setContentType("text/html"); HttpSession session = req.getSession(true); Order order = parseOrder(req); BookChoiceServlet session.setAttribute("order",order); outputPostText(req, resp); doPost( ) } outputPostText( ) parseOrder( )

  15. Book Choice Servlet (2 of 2) BookChoiceServlet public Order parseOrder (HttpServletRequest req) { Order order = new Order(); SaleLineItem line = null; Enumeration enum = req.getParameterNames(); while (enum.hasMoreElements()) { String name = (String) enum.nextElement(); String info = req.getParameter(name); line = SaleLineItem.create(name, info); if (line != null) order.addLineItem(line); } return order; } doGet( ) doPost( ) outputGetText( ) outputPostText( ) parseOrder( )

  16. Credit Information Servlet public void doPost(..) { res.setContentType("text/html"); HttpSession session = req.getSession(false); if (session != null) { Customer cust = parseCustomer(req); Address addr = parseAddress(req); cust.setAddress(addr); Order order = (Order) session.getAttribute("order"); order.setCustomer(cust); processOrder(order); outputPostText(out,order); } else { /* process error */ } } CreditInformationServlet doPost( ) outputPostText( ) parseAddress( ) parseCustomer( ) processOrder( )

  17. Thread Safety • The HttpSession object is a shared resource • Access to shared objects should be synchronized • Do not synchronize indirectly (for example, synchronizing various servlets’ doPost() methods) • Instead, wrap sets of setAttribute() and getAttribute() in a synchronized block Customer cust = (Customer) session.getAttribute("customer"); synchronized (cust) { // work with the customer object }

  18. HttpSession Classes HttpServletRequest getSession( ) HttpSession HttpSessionBindingListener <<interface>> getAttribute(String) setAttribute(String,Object) valueBound(HttpSessionBindingEvent) removeAttribute(String) valueUnbound(HttpSessionBindingEvent) key : String UserObject

  19. Session Serialization • Objects stored in a session must be serializable: • To share between servers in a clustered server configuration • For persistence to work • Make sure objects reachable from the session are also serializable • When creating objects to be stored in the session, implement the serializable interface: public class NewObject implements java.io.Serializable { ... }

  20. Servlet Objects (1 of 4) HttpSession ServletResponse ServletRequest Servlet A Client Sue Servlet A Thread 1 ServletConfig Servlet A Thread 2 ServletContext Client Bob HttpSession ServletResponse ServletRequest

  21. Servlet Objects (2 of 4) HttpSession ServletResponse ServletRequest Servlet A Client Sue Servlet A Thread 1 ServletConfig Servlet A Thread 2 Client Sue ServletContext ServletResponse ServletRequest

  22. Servlet Objects (3 of 4) HttpSession ServletResponse ServletRequest ServletConfig Client Sue Servlet A ServletContext Servlet B ServletConfig Client Bob HttpSession ServletResponse ServletRequest

  23. Servlet Objects (4 of 4) HttpSession ServletResponse ServletRequest ServletConfig Client Sue Servlet A ServletContext Servlet B Client Sue ServletConfig ServletResponse ServletRequest

  24. WebSphere Extensions • WebSphere provides an extension to HttpSession in the interface: com.ibm.servlet.websphere.servlet.session.IBMSession • Extends HttpSession for session support and increased Web administrators' control in a session cluster environment • Has the following additional methods: • public String getUserName() – identifies the authenticated owner of the session • public boolean isOverflow() – determines if the session is valid when hard limits are set on the session manager • public void sync() – used to perform an early commit on session transaction • WebSphere extensions are not portable across J2EE application servers

  25. Checkpoint • Explain how to invalidate a session. • Why do we need to be concerned with thread safety? • Why would we need to serialize a session? • What are the WebSphere extensions to the HttpSession interface?

  26. Checkpoint solutions • As session is invalidated by being inactive too long, by being explicitly invalidated (HttpSession's invalidate() method), or when the client browser closes (if a cookie is being used to manage the session). • If multiple browsers within the same client are sharing the same session, getting/setting the attributes should be synchronized. • If the successive requests within the same session execute on different servers/JVMs, the session object and attributes may need to be serialized to be moved among the different servers. • sync(), getUserName(), isOverflow()

  27. Unit summary Having completed this unit, you should be able to: • Discuss the task of managing client application data • Session Management • Describe the use of HttpSession to maintain a user session • Describe how object sharing is implemented in the servlet environment • Describe the various ways to manage application state