27
® IBM Software Group © 2007 IBM Corporation HttpSession: Management of Application Data 4.1.0 .3

HttpSession: Management of Application Data

Embed Size (px)

DESCRIPTION

HttpSession: Management of Application Data. 4.1.0.3. 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 - PowerPoint PPT Presentation

Citation preview

®

IBM Software Group

© 2007 IBM Corporation

HttpSession: Management of Application Data

4.1.0.3

2

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

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

Unit objectives

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 forthApplication involves several ServletsServlets need to be stateless

Multiple implementation technologies including:HttpSession HTTP CookiesHTML Hidden FieldURL 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 connectionLifetime spans multiple servlets and page requestsIs identified within requests via a Session identifier

5

Session Usage Servlet asks to bind to the Session object representing the

current sessionrequest.getSession(boolean create)Method returns the current HttpSession, if it existsIf 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 closedThe session is explicitly invalidatedThe 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

ID value

MKA42O... SessionR1

...

...

YM4YLEI... SessionA3

SessionA3key value

"customer" aCustomer

"name" "Bob"

Application Server

Session Table

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

8

Cookie List

Browser

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 HttpServletResponseNo automatic support in JSP

pagesRequires ad hoc support for

client-side script generated URLs

9

ID value

MKA42O... SessionR1

...

...

YM4YLEI... SessionA3

SessionA3key value

"customer" aCustomer

"name" "Bob"

Application Server

Session Table

cookie name value domain

"JSESSIONID" YM4YLEI... .ibm.com

Cookie List

Browser

Sessions at Run Time

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 timeoutsession.invalidateRemoves all values from the session

The Session timeout (inactive interval) can be set for the application server as a wholeThe default timeout is 30 minutes

Also session.setMaxInactiveInterval(int) can provide session-specific timeout value

11

Session Invalidation Exampleimport 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;

public class ApplicationLogoutServlet extends HttpServlet {

public void 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

Address

zip : String

city : String

state : String

streetAddress : String

SaleLineItem

price : double

itemName : String

customer

Customer

name : String

creditCardNumber : String

creditCardExpiration : String

Order

lineItems

1

1

1 0..*

0..*

1

Bookstore Domain Classes

14

public void doPost(req, resp) { resp.setContentType("text/html"); HttpSession session = req.getSession(true); Order order = parseOrder(req); session.setAttribute("order",order); outputPostText(req, resp);}

BookChoiceServlet

outputPostText( )parseOrder( )

doPost( )

Book Choice Servlet (1 of 2)

15

BookChoiceServlet

outputGetText( )outputPostText( )parseOrder( )

doGet( )doPost( )

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

Book Choice Servlet (2 of 2)

16

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

parseAddress( )

outputPostText( )

doPost( )

parseCustomer( )

processOrder( )

Credit Information Servlet

17

Thread Safety The HttpSession object is a shared resource

Access to shared objects should be synchronizedDo 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

UserObject

HttpSessionBindingListener

valueBound(HttpSessionBindingEvent)valueUnbound(HttpSessionBindingEvent)

HttpServletRequest

getSession( )

HttpSession

getAttribute(String)setAttribute(String,Object)removeAttribute(String)

<<interface>>

key : String

HttpSession Classes

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 A

Servlet AThread 1

Servlet AThread 2

ServletRequestHttpSessionServletResponse

ServletConfig

ServletResponseServletRequest

ServletContext

HttpSession

Client Bob

Client Sue

Servlet Objects (1 of 4)

21

Servlet A

Servlet AThread 1

Servlet AThread 2

ServletRequestHttpSession ServletResponse

ServletConfig

ServletResponseServletRequest

ServletContext

Client Sue

Client Sue

Servlet Objects (2 of 4)

22

Servlet A

Servlet B

ServletRequestHttpSession ServletResponse

ServletResponseServletRequestHttpSession

Client Bob

Client SueServletConfig

ServletContext

ServletConfig

Servlet Objects (3 of 4)

23

Servlet A

Servlet B

ServletRequestHttpSession ServletResponse

ServletConfig

ServletResponseServletRequest

ServletContext

Client Sue

Client Sue

ServletConfig

Servlet Objects (4 of 4)

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

1. Explain how to invalidate a session.2. Why do we need to be concerned with thread safety?3. Why would we need to serialize a session?4. What are the WebSphere extensions to the HttpSession

interface?

26

Checkpoint solutions

1. 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).

2. If multiple browsers within the same client are sharing the same session, getting/setting the attributes should be synchronized.

3. 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.

4. sync(), getUserName(), isOverflow()

27

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

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

Unit summary