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

HttpSession: Management of Application Data

Jan 02, 2016

Download

Documents

keely-morrison

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
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: HttpSession: Management of Application Data

®

IBM Software Group

© 2007 IBM Corporation

HttpSession: Management of Application Data

4.1.0.3

Page 2: HttpSession: Management of Application Data

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

Page 3: HttpSession: Management of Application Data

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

Page 4: HttpSession: Management of Application Data

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

Page 5: HttpSession: Management of Application Data

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

Page 6: HttpSession: Management of Application Data

6

HttpSession Data Store HttpSessions store application-specific information

Stored as <"key", object> pairs void setAttribute(String, Object) Object getAttribute(String)

Page 7: HttpSession: Management of Application Data

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

Page 8: HttpSession: Management of Application Data

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

Page 9: HttpSession: Management of Application Data

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

Page 10: HttpSession: Management of Application Data

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

Page 11: HttpSession: Management of Application Data

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

}

}

Page 12: HttpSession: Management of Application Data

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

Page 13: HttpSession: Management of Application Data

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

Page 14: HttpSession: Management of Application Data

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)

Page 15: HttpSession: Management of Application Data

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)

Page 16: HttpSession: Management of Application Data

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

Page 17: HttpSession: Management of Application Data

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

}

Page 18: HttpSession: Management of Application Data

18

UserObject

HttpSessionBindingListener

valueBound(HttpSessionBindingEvent)valueUnbound(HttpSessionBindingEvent)

HttpServletRequest

getSession( )

HttpSession

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

<<interface>>

key : String

HttpSession Classes

Page 19: HttpSession: Management of Application Data

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 {

...}

Page 20: HttpSession: Management of Application Data

20

Servlet A

Servlet AThread 1

Servlet AThread 2

ServletRequestHttpSessionServletResponse

ServletConfig

ServletResponseServletRequest

ServletContext

HttpSession

Client Bob

Client Sue

Servlet Objects (1 of 4)

Page 21: HttpSession: Management of Application Data

21

Servlet A

Servlet AThread 1

Servlet AThread 2

ServletRequestHttpSession ServletResponse

ServletConfig

ServletResponseServletRequest

ServletContext

Client Sue

Client Sue

Servlet Objects (2 of 4)

Page 22: HttpSession: Management of Application Data

22

Servlet A

Servlet B

ServletRequestHttpSession ServletResponse

ServletResponseServletRequestHttpSession

Client Bob

Client SueServletConfig

ServletContext

ServletConfig

Servlet Objects (3 of 4)

Page 23: HttpSession: Management of Application Data

23

Servlet A

Servlet B

ServletRequestHttpSession ServletResponse

ServletConfig

ServletResponseServletRequest

ServletContext

Client Sue

Client Sue

ServletConfig

Servlet Objects (4 of 4)

Page 24: HttpSession: Management of Application Data

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

Page 25: HttpSession: Management of Application Data

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?

Page 26: HttpSession: Management of Application Data

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

Page 27: HttpSession: Management of Application Data

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