scwcd : session management : chap : 6

78
1 Session Management Helmi ben abdallah @rchitect JEE

Upload: oxia

Post on 09-Apr-2017

217 views

Category:

Technology


2 download

TRANSCRIPT

Page 1: SCWCD : Session management : CHAP : 6

1

Session Management

Helmi ben abdallah @rchitect JEE

Page 2: SCWCD : Session management : CHAP : 6

2

THE FOLLOWING SUN CERTIFIED WEB COMPONENT DEVELOPER FOR J2EE PLATFORM EXAM OBJECTIVES COVERED IN THIS CHAPTER:

5.1 Identify the interface and methods for each of the following:• Retrieve a session object across multiple requests to the same or different

servlets within the same WebApp• Store objects into a session object• Retrieve objects from a session object• Respond to the event when a particular object is added to a session• Respond to the event when a session is created and destroyed• Expunge a session object5.2 Given a scenario, state whether a session object will be invalidated.

5.3 Given that URL rewriting must be used for session management, identify the design requirements on sessionrelated HTML pages.

Page 3: SCWCD : Session management : CHAP : 6

3

Page 4: SCWCD : Session management : CHAP : 6

4

• When a client accesses a web application, they often supply information that will be used by the application at a later period during the conversation. If this information could not be retained, the application would need to ask for the information again. This is both time-consuming and inefficient. • A servlet’s session object is used to resolve this issue. Sessions

provide various ways to monitor and maintain client data. In this chapter, we will address how to:

• Track a client’s session• Change a session’s data• Respond to the creation or destruction of a session object and

its attributes• Invalidate a session

Page 5: SCWCD : Session management : CHAP : 6

5

Tracking Sessions• When a client interacts with a server application, that client is

likely to make multiple requests to achieve a particular goal. Because the HTTP protocol is stateless, it closes its connection after each request. • client data stored within a request is available for only a short

period of time.• For a client object with a longer lifespan, a session is used. A• session object is usually created when a client makes its first

request to an application.• It is unique to a client and can exist longer than a single

request or even longer than the life of a client.• It is an object used to track client-specific data for the duration

of the conversation or a specified period of time.

Page 6: SCWCD : Session management : CHAP : 6

6

• What distinguishes one session from another is its unique ID. In fact, the container uses this ID to map an incoming request to the correct session object, which in turn is associated to a particular client. • The actual client information can be transferred by using

one of three session processes:

1. Using hidden form fields2. Rewriting the URL3. Using cookies

Page 7: SCWCD : Session management : CHAP : 6

7

Using Hidden Form Fields

• Transferring information between an HTML form and a servlet can be done in several ways.• The most basic procedure is to transfer information back

and forth as data values. A form can contain fields with client-cached values passed between each request. • Because this information does not need to be visible to

the client, it is marked by using a field type of hidden

Page 8: SCWCD : Session management : CHAP : 6

8

Imagine the following web application scenario:1.A login screen is displayed.2.The user enters their login name and password.3.The servlet verifies the information and returns a web page for the client to

utilize the company’s services.4.The new page stores the client’s login name from the previous servlet.This information is not visible to the client, but is needed for checkout

purposes.By using hidden HTML values , you can store client data between servlets to use at a later date. The following HTML code produces the login screen used for this scenario:

Page 9: SCWCD : Session management : CHAP : 6

9

• After the user enters their login name and password, they trigger the request by clicking the submit button. The servlet then verifies the information and constructs a response containing the client’s information.• The following code shows this process. (Pay particularly

close attention to the bold text. It highlights how hidden values are transferred.)

Page 10: SCWCD : Session management : CHAP : 6

10

Page 11: SCWCD : Session management : CHAP : 6

11

Page 12: SCWCD : Session management : CHAP : 6

12

• Tracking each hidden value in each servlet can become tedious. Unfortunately,as the session persists and information increases, passing hidden data back and forth can become taxing.

• The session can persist only through dynamically generated pages. If there is a need to display static, e-mail, or bookmarked documents, the session will be lost.

• Hidden value transfers are the least secure method of maintaining information between pages. Because HTTP transfers all data as clear text, it can be intercepted, extracted, and manipulated. If someone were watching the transmission between client and server, they could easily read information such as the login ID and password.

Page 13: SCWCD : Session management : CHAP : 6

13

Rewriting the URL

• Anonymous session tracking can also be done by using a technique called URL rewriting. • This approach to session tracking is used when clients do not

accept cookies (URL rewriting is a methodology that associates a session ID to all URL addresses used throughout the session. • Using the ID, a developer can map client-related data to the

session object for that client. • The ID is temporarily stored until the session has ended. After

the session has ended, the ID and related data are discarded.

Page 14: SCWCD : Session management : CHAP : 6

14

• Keep in mind that it is important for the session ID to have a standard name that all containers can recognize. • The specification defines that name as jsessionid . A

standardized name enables the container to associate requests to their session objects stored on the server.• There are two methodologies used to rewrite a URL. > One approach is to manually adjust the URL to include the session

ID, > the second approach is to use provided API methods to encode the

URL.

Page 15: SCWCD : Session management : CHAP : 6

15

Manual URL Rewriting

• Manually rewriting a URL can be done by physically adding the ID to the constructed URL. How the ID is stored and accessed from within the URL can vary.

Page 16: SCWCD : Session management : CHAP : 6

16

In this section, we will show you how to rewrite the URL by adding a session ID to the URL path. But first, let’s talk about how the ID is generated.

The goal is to derive a value that is completely random and not shared. The Remote Method Invocation (RMI) API provides several methods that help develop such a method.

The common procedure is to create a method that does the following:

public static String generateSessionID(){String uid = new java.rmi.server.UID().toString();return java.net.URLEncoder.encode(uid);}

Page 17: SCWCD : Session management : CHAP : 6

17

Now you’re ready to learn how to “rewrite” the URL to contain the session ID. We’ll begin by revisiting the URL structure:

Request URL = contextPath + servletPath + pathInfo+querystringGiven a request URL of /games/Chess , you can break the pieces

into their defined categories:Context path:/gamesServlet path: /ChessPath info: /nullQuery string: /null

Page 18: SCWCD : Session management : CHAP : 6

18

If you had a session ID with the value 567, that ID could be incorporated into the URL by adding it to the path info section, as follows:

/games/Chess/567Literally, this can be done by concatenating the session ID to the ACTION

value’s URL. For example:out.println("<FORM ACTION=’/games/Bingo/"+ sessionID + "/” Method=’POST’>");out.println("<INPUT TYPE='submit' VALUE='Bingo'>");

When the button is pressed, the current URL is switched to /games/Bingo/567. This new servlet page provides the session ID within the URL, which enables the developer to extract any data stored from previously accessed servlets. To access the session ID, use the HttpServletRequest method getPathInfo(). This method returns extraneous information between the servlet and the query string.

Page 19: SCWCD : Session management : CHAP : 6

19

you would expect to have a utility class for writing data and its associated session ID to a location. The class should also provide functionality to retrieve the client data based on a unique session ID.

Page 20: SCWCD : Session management : CHAP : 6

20

Sample URL-rewriting application

Page 21: SCWCD : Session management : CHAP : 6

21

Page 22: SCWCD : Session management : CHAP : 6

22

Page 23: SCWCD : Session management : CHAP : 6

23

Page 24: SCWCD : Session management : CHAP : 6

24

Using Methods to Encode the URL

• Instead of manually generating a session ID and physically adding it to the URL, the API provides methods that manage the task for the developer. • The HttpServletResponse class offers the following two

methods:• public String encodeURL(java.lang.String url)• public String encodeRedirectURL(java.lang.String url)The encodeURL(…) method rewrites the specified URL to include a session ID if needed. If one is not needed, the method returns the original URL.

An unchanged URL can result from a server that does not support URL rewriting or from a server that has the feature turned off. As for the semantics of how the URL is encoded, that feature or technique is server-specific.

Page 25: SCWCD : Session management : CHAP : 6

25

• The second method is similar to the first in that it, too, encodes the passed-in URL by adding the session ID. It differs, however, in when it is used.• At times there is a need for a servlet to temporarily redirect

a response to a different location.• This is done by using the HttpServletResponse’s method

sendRedirect(String url). Before calling this method, the URL should be encoded by using a method specifically designed to handle URL encoding for a redirected response: encodeRedirectURL(String url).

• The reason for using a different method is that a redirect URL is different from a normal URL. For a redirect URL, all non-ASCII values must be converted to their hexadecimal values; this includes ampersands and equal Signs

Page 26: SCWCD : Session management : CHAP : 6

26

The following is an example of a rewritten URL:http://localhost:8080/servlet/CheckOutServlet jsessionid=4347To encode links in your URL, you must make slight modifications to the HTML code.

Here is an example of how to rewrite the URL to include an encoded URL in a form:

String urlSession = res.encodeURL("/servlet/CheckOutServlet");out.println("<FORM ACTION=’" + urlSession + "‘” +“ Method='POST'>");out.println("<INPUT TYPE='submit' VALUE=’ Exit ‘>");out.println("</FORM></BODY></HTML>");If your intent is to encode a URL for a link, you simply include an

encodedString instead of the standard URL:out.println(“Click “ + “<A HREF=’”+

res.encodeURL(“/servlet/CheckOutServlet”) + “‘>here</A>”);

Page 27: SCWCD : Session management : CHAP : 6

27

• In order for the container to encode the URL with a session ID, three conditions usually exist:• The browser supports URL encoding.• The browser does not support cookies.• The session tracking feature is turned on.• When using the encodeURL(…) method, the session ID is

stored as a path parameter. As such, you must call req.getPathInfo() to retrieve the ID value.

You can also access the ID by calling req.getSession() to acquire a handle to the actual session object (assuming one exists). Using the session instance, the ID value can then be accessed by calling session.getId().

Page 28: SCWCD : Session management : CHAP : 6

28

• The servlet can also use the following HttpServletRequest methods to learn more about the methodology used to generate the ID, as well as its validity:• public boolean isRequetedSessionIdFromCookie()• public boolean isRequestedSessionIdFromURL()• public boolean isRequestedSessionIdValid()

• These methods validate the session object and its place of origin. If the session is not valid, the servlet can redirect the user to a new screen to log in again. If the session ID was obtained from the URL, the servlet might opt to perform a different task than if it was obtained from a cookie.

Page 29: SCWCD : Session management : CHAP : 6

29

Using Cookies• Another way to perform session tracking is through

persistent cookies.• Remember, a cookie is an object containing small amounts

of information sent by a servlet to a web browser, then saved by the browser, and later sent back to the server. • Because the cookie’s value can uniquely identify a client

and maintain client data, using cookies is an optimal way to track sessions.• A cookie is created by using two parameters: a name and a

value. The constructor is as follows:• public Cookie(String name, String value)• Unlike a hidden value, which must exist in all servlet pages,

a cookie is added to the servlet’s response object and is propagated to all servlets accessed during the session.

Page 30: SCWCD : Session management : CHAP : 6

30

• The servlet specification mandates that the name of the value used to track the session for a cookie must be called JSESSIONID.

• The ID name must be all uppercase when used within a cookie, but lowercase when used in URL rewriting.

• A cookie can be added to an HttpServletResponse object in the following way:

• Cookie cookie = new Cookie(“JSESSIONID”, “567”);• res.addCookie(cookie);• If another servlet is interested in accessing this information, it can call the• getCookies() method of the HttpServletRequest class:• public Cookie[] getCookies() • Using our example from the preceding “Rewriting the URL” section, you• can create a cookie to add the session ID. Listing 6.4 demonstrates how

to use cookies to rewrite the OverviewServlet.

Page 31: SCWCD : Session management : CHAP : 6

31

Page 32: SCWCD : Session management : CHAP : 6

32

Page 33: SCWCD : Session management : CHAP : 6

33

Using the HttpSession Object

• The final and most convenient way to handle session data is to pass an HttpSession object, which implicitly contains the client’s data, back and forth between all session-related servlets.

Page 34: SCWCD : Session management : CHAP : 6

34

Using the HttpSession Object

• Previously, we discussed ways to track the session object between client/ server requests, where each example (cookie or URL rewriting) used a database for persistent storage of session data. • In this section, the HttpSession object replaces the

database for persistent storage, and uses one of the methods previously discussed to propagate the session ID.• Internally, the container determines the method used to

transmit the session ID between the client and server (whether it used cookies or URL rewriting).

Page 35: SCWCD : Session management : CHAP : 6

35

• To access a session object, use the HttpServletRequest method:• public HttpSession getSession()• The method returns the HttpSession object tied to the

client requesting the current servlet. If the object does not exist, the getSession() method will automatically create a new HttpSession instance.• The other method used to access a session object is as

follows:• public HttpSession getSession(boolean create)• A true value creates a new session object if one does not

already exist.• A false value prevents a session object from being

created if one does not exist.

Page 36: SCWCD : Session management : CHAP : 6

36

• Data is stored to an HttpSession object as attributes:• public void setAttribute(String name, Object value)• The setAttribute(…) method binds a Java object to a

specified key name. Another servlet can then use the HttpSession object and access its data by using the following method:• public Object getAttribute(String name)• The getAttribute(…) method uses the key name to find

and return the associated object.

Page 37: SCWCD : Session management : CHAP : 6

37

Remember, each application has one ServletContext, and each context has multiple sessions for each client that accesses the application.

Page 38: SCWCD : Session management : CHAP : 6

38

• Adding an attribute is as easy as removing one. To unbind an attribute, call the method:• public void removeAttribute(String name)• After this method is invoked on an attribute, it is no longer

accessible by any servlet within the application.• list all the attributes associated with the current session:• public Enumeration getAttributeNames()• The getAttributeNames() method returns an Enumeration

object of all current attributes. If a session has no attributes, a null value is returned.• Sometimes there is a need to respond to changes to a

session’s attributes. The servlet API provides several session listener classes designed specifically for this purpose. HttpSessionBindingListener

Page 39: SCWCD : Session management : CHAP : 6

39

HttpSessionBindingListener

• By implementing the HttpSessionBindingListener, your application can be notified when an object is bound or unbound to a session object. • The interface has two primary methods that must be

defined:• valueBound(HttpSessionBindingEvent event)• valueUnbound(HttpSessionBindingEvent event)

Page 40: SCWCD : Session management : CHAP : 6

40

• The valueBound(…) method is called before the object is made available through the getAttribute(…) method. • In contrast, the valueUnbound(…) method is called after

the object is no longer available via the getAttribute(…) method of the HttpSession interface. • The listener is passed an HttpSessionBindingEvent,

which contains the session object, the name, and the value of the object either bound or unbound to the session.

Page 41: SCWCD : Session management : CHAP : 6

41

• To register session listeners to the container, you must include the listener tag in the web.xml document.• For example:<listener> <listener-class> ConnectionPoolHandler </listener-class></listener>• The container determines the type of listener defined and

then establishes an abstract link between the session and the listener. • When changes occur to the session, the appropriate listener

is notified.

Page 42: SCWCD : Session management : CHAP : 6

42

Invalidating Sessions• A session can be invalidated in multiple ways. It can

expire automatically,after a specified or default period of inactivity, or a servlet can explicitly invalidate a session through method calls. • Before learning about these options, it is important to

understand the effects on the application and client when a session is nullified.• Basically, all the attribute data is lost.• If you want to retain session information after it is

invalidated, it should be stored to an external resource such as a database or a long-term cookie.

Page 43: SCWCD : Session management : CHAP : 6

43

The session-time tag defines the number of inactive minutes a session will exist before the server terminates the object.

The following is sample code for the web.xml file used to change the default termination period:

<web-app><session-config><session-timeout>15 </session-timeout></session-config></web-app>

The servlet specification requires that the timeout value be specified in whole numbers. Some servers allow the use of negative values to indicate that sessions should not be terminated

Page 44: SCWCD : Session management : CHAP : 6

44

• A second approach to modifying the life of a session is to have individual servlets define the inactive time period before a session is destroyed. • The HttpSession interface provides the following methods:> public void setMaxInactiveInterval(int secs)> public int getMaxInactiveInterval()

• These methods allow fine-grained control. Instead of applying a time period to the entire application, you can set the time to specific servlets. • The benefit of this approach is that you can customize the

timeout period per user or after certain activities have taken place, such as a lengthy database lookup.

Notice that the time is measured in seconds rather than minutes

Page 45: SCWCD : Session management : CHAP : 6

45

• The getMaxInactiveInterval() method returns the value set. If the set method is not used and the time is set by using the session-timeout tag, the getMaxInactiveInterval() method will return the timeout value defined within the web.xml file.

Page 46: SCWCD : Session management : CHAP : 6

46

The third approach is pretty abrupt. The HttpSession interface providesthe following method:• public void invalidate() throws IllegalStateException• After a handle to the session is obtained, the invalidate()

method can be called to close the session and unbind all associated objects.• If the session is already invalidated, then an

IllegalStateException object is thrown.

Page 47: SCWCD : Session management : CHAP : 6

47

Now that we’ve covered how to end a session, it is important for you to understand the best practices associated to a session’s timeout period.

Page 48: SCWCD : Session management : CHAP : 6

48

Review Questions

Page 49: SCWCD : Session management : CHAP : 6

49

1. Which of the following best describes an example of URL rewriting?

A. out.println("<INPUT TYPE=hidden NAME='name' VALUE= BillyBob>");

B. out.println("<FORM ACTION=’/servlet/TestServlet/BillyBob’ METHOD=POST>");C. HttpSession session = req.getSession();D. session.addAttribute(“name”, “BillyBob”);E. None of the above

Page 50: SCWCD : Session management : CHAP : 6

50

• 1. B. URL rewriting consists of adding data to the URL. The receiving servlet can then extract the additional information to utilize the data.

Page 51: SCWCD : Session management : CHAP : 6

51

2. Which interface provides the method getSession()?A. ServletRequestB. ServletResponseC. HttpServletResponseD. HttpServletRequest

Page 52: SCWCD : Session management : CHAP : 6

52

• 2. D. A session is reliant on HTTP transactions. Because the application’s communication with the client is through the HttpServletRequest interface, and the session is not transmitted back to the client, the session object is obtained via the HttpServletRequest interface.

Page 53: SCWCD : Session management : CHAP : 6

53

3. Which of the following methods is used to store objects into a session object?

A. setData(String name, Object obj)B. setDataAttribute(String name, Object obj)C. setAttribute(String name, String obj)D. setAttribute(String name, Object obj)

Page 54: SCWCD : Session management : CHAP : 6

54

• 3. D. The setAttribute(String name, Object obj) method binds• an object with a related key name to the session object.

The other• methods are all illegal.

Page 55: SCWCD : Session management : CHAP : 6

55

4. Which of the following methods is used to expunge a session object?

A. end()B. destroy()C. invalidate()D. kill()

Page 56: SCWCD : Session management : CHAP : 6

56

• 4. C. The invalidate() method terminates the associated session and• then unbinds any objects bound to it.

Page 57: SCWCD : Session management : CHAP : 6

57

5. Which of the following is not a valid methodology for session management?

A. CookiesB. HttpSession objectsC. Hidden valuesD. ServletContext object

Page 58: SCWCD : Session management : CHAP : 6

58

• 5. D. The ServletContext is associated with the web application, not with the individual client session. Consequently, data stored to the context is not unique to a client.

Page 59: SCWCD : Session management : CHAP : 6

59

6. The session-timeout tag defines the number of inactive _________ a session will exist before being terminated.

A. MillisecondsB. SecondsC. MinutesD. Hours

Page 60: SCWCD : Session management : CHAP : 6

60

• 6. C. The timeout tag defines the minimum number of minutes of inactivity that can pass before a session can be inactive before being terminated by the server.

Page 61: SCWCD : Session management : CHAP : 6

61

7. Which of the following statements is invalid?A. The session timeout value determines how long a

session lasts.B. A session is associated with a client.C. The setMaxInactiveInterval(…) method is used by the

servlet via the HttpSession object.D. If a session timeout is not set, the server will

terminate sessions by using a default time value.

Page 62: SCWCD : Session management : CHAP : 6

62

• 7. A. A session timeout value tells the amount of time the session will stay alive only during an inactive period, not its entire life.

Page 63: SCWCD : Session management : CHAP : 6

63

8. What is the recommended timeout period that a shopping cart application should have?

A. ShortB. MediumC. LongD. Irrelevant

Page 64: SCWCD : Session management : CHAP : 6

64

• 8. C. Because a client usually collects multiple items in a cart, a shortlived inactive period could cause problems and irritation to the user.• This could result in a loss of business because the user

might not want• to return or might forget what they already selected.

Page 65: SCWCD : Session management : CHAP : 6

65

9. Which of the following best describes what is returned when the getMaxInactiveInterval() method is called?

A. The default inactive timeout period, in minutes, for a session to exist before termination.

B. The number of seconds an inactive session can exist when using the setMaxInactiveInterval(int sec) method.

C. The default inactive timeout period, in seconds, for a session to exist before termination.

D. It depends on how the server or application handles the session timeout period.

Page 66: SCWCD : Session management : CHAP : 6

66

• 9. D. Depending on how the session timeout period is set, the• getMaxInactiveInterval() method will return the number of• seconds that the inactive session will exist before

termination.

Page 67: SCWCD : Session management : CHAP : 6

67

10. Which of the following is not a valid way to change the inactive period of a session before the server terminates the session?

A. <session-timeout>60</session-timeout>B. setMaxInactiveInterval(500)C. <session-config>30</session-config>D. Do nothing

Page 68: SCWCD : Session management : CHAP : 6

68

• 10. C. The session-config tag requires the session-timeout tag to• define the number of minutes a session can be inactive.

As for doing• nothing, the server usually has a default inactive period

defined• automatically.

Page 69: SCWCD : Session management : CHAP : 6

69

11. Which of the following methods is used to retrieve a bound session object?

A. getBoundObject(String name)B. getData(String name)C. getSessionObject(String name)D. getAttribute(String name)

Page 70: SCWCD : Session management : CHAP : 6

70

• 11. D. The getAttribute(String name) method returns the object bound to the session by using the associated name reference.

Page 71: SCWCD : Session management : CHAP : 6

71

12. Which of the following is an example of URL rewriting by using the encodeURL(String url) method? (Choose all that apply.)

A. http://localhost:8080/servlet/play;jsessionid=567B. http://localhost:8080/servlet/playC. http://localhost:8080/servlet/play?jsessionid=567D. None of the above

Page 72: SCWCD : Session management : CHAP : 6

72

• 12. A, B. The encodeURL(String url) method encodes the specified• URL by including the session ID in it. If encoding is not

needed, the• method returns the URL unchanged.

Page 73: SCWCD : Session management : CHAP : 6

73

13. Which of the following methods is called when an object is removed from a session object?

A. valueUnbound(HttpSessionEvent e)B. valueUnBound(HttpBindingSessionEvent e)C. valueUnbound(HttpSessionBindingEvent e)D. valueUnBound(HttpSession e)

Page 74: SCWCD : Session management : CHAP : 6

74

• 13. C. The valueUnbound, lowercase b, method is called when an object• is unbound from the session object. An

HttpSessionBindingEvent is• passed to the method containing the session object, and

the name and• value of the object removed can be gathered from this

event object.

Page 75: SCWCD : Session management : CHAP : 6

75

14. Which of the following statements is true?A. The valueBound(…) method is called before the

object is made available through the getAttribute() method.

B. The valueBound(…) method is called after the object is made available through the getAttribute() method.

C. The valueBound(…) method is called at different times depending on the server’s preference.

D. None of the above

Page 76: SCWCD : Session management : CHAP : 6

76

• 14. A. The servlet specification mandates that the valueBound(…)• method should be called before the object is made

available through• the getAttribute() method.

Page 77: SCWCD : Session management : CHAP : 6

77

15. Which of the following listeners is called when a session is destroyed?

A. HttpSessionBindingListenerB. HttpSessionListenerC. HttpSessionChangedListenerD. SessionListener

Page 78: SCWCD : Session management : CHAP : 6

78

• 15. B. The HttpSessionListener is called when a session is created and• destroyed