Sessions Sessions Many interactive Web sites spread user
Sessions
Sessions • Many interactive Web sites spread user data entry out over several pages, Examples: • add items to cart • enter shipping information • enter billing information • etc. • Problem: how does the server know which users generated which HTTP requests? • Cannot rely on standard HTTP headers to identify a user, Why!? ?
What is a Session? • A session is a state associated with particular user that is maintained at the server side • Sessions should persist between the HTTP requests • Sessions enable creating applications that depend on individual user data. For example: • Login / logout functionality • Wizard pages • Shopping carts • Personalization services • Maintaining state about the user’s preferences • etc.
Sessions in Servlets • Servlets include a built-in Sessions API • Sessions are maintained automatically, with no additional coding • The Web container associates a unique Http. Session object to each different client • Different clients have different session objects at the server • Requests from the same client have the same session object • Sessions can store various data
Sessions
Sessions Server sends back new unique session ID when the request has none 6
Sessions Client that supports session stores the ID and sends it back to the server in subsequent requests 7
Sessions Server knows that all of these requests are from the same client. The set of requests are known as a session. 8
Sessions And the server knows that all of these requests are from a different client. 9
Sessions Returns Http. Session object associated with this HTTP request. • Creates new Http. Session object if no session ID in request or no object with this ID exists • Otherwise, returns previously created object
Sessions Boolean indicating whether returned object was newly created or already existed. Incremented once per session
Sessions Three web pages produced by a single servlet
Sessions 13
Sessions , , , Session attribute will have null value until a value is assigned Session attribute is a name/value pair
Sessions , , , Generate sign-in form if session is new or sign. In attribute has no value, weclome-back page otherwise.
Sessions Sign-in form Welcome-back page
Sessions • Session attribute methods: • set. Attribute(String name, Object value) • Creates a session attribute with the given name and value • Object get. Attribute(String name) • Returns the value of the session attribute named name, or returns null if this session does not have an attribute with this name
Sessions • By default, each session expires if a server-determined length of time elapses between a session’s HTTP requests • Server destroys the corresponding session object • Servlet code can: • Terminate a session by calling invalidate() method on session object • Set the expiration time-out duration (secs) by calling set. Max. Inactive. Interval(int)
The Sessions API • The sessions API allows • To get the Http. Session object from the HTTPServlet. Request object • Extract data from the user’s session object • Append data to the user’s session object • Extract meta-information about the session object, • e. g. when was the session created
Getting The Session Object • To get the session object use the method Http. Servlet. Request. get. Session() • Example: Http. Session session = request. get. Session(); • If the user already has a session, the existing session is returned • If no session still exists, a new one is created and returned • If you want to know if this is a new session, call the is. New() method
Behind The Scenes • When you call get. Session() each user is automatically assigned a unique Session ID • How does this Session ID get to the user? • Option 1: • If the browser supports cookies, the servlet will automatically create a session cookie, and store the session ID within the cookie • In Tomcat, the cookie is called JSESSIONID • Option 2: • If the browser does not support cookies, the servlet will try to extract the session ID from the URL
Extracting Data From The Session • The session object works like a Hash. Map • Enables storing any type of Java object • Objects are stored by key (like in hash tables) • Extracting existing object: Integer access. Count = (Integer) session. get. Attribute("access. Count"); • Getting a list of all “keys” associated with the session Enumeration attributes = request. get. Attribute. Names();
Storing Data In The Session • We can store data in the session object for using it later Http. Session session = request. get. Session(); session. set. Attribute("name", “SE 432"); • Objects in the session can be removed when not needed more session. remove. Attribute("name");
Getting Additional Session Information • Getting the unique session ID associated with this user, e. g. gj 9 xswvw 9 p public String get. Id(); • Checking if the session was just created public boolean is. New(); • Checking when the session was first created public long get. Creation. Time(); • Checking when the session was last active public long get. Last. Accessed. Time();
Session Timeout • We can get the maximal session validity interval (in seconds) public int get. Max. Inactive. Interval(); • After such interval of inactivity the session is automatically invalidated • We can modify the maximal inactivity interval public void set. Max. Inactive. Interval (int seconds); • A negative value specifies that the session should never time out
Terminating Sessions • To terminate session manually use the method: public void invalidate(); • Typically done during the "user logout" • The session can become invalid not only manually • Sessions can expire automatically due to inactivity
Login / Logout – Example • We want to create a simple Web application that restricts the access by login form • We will use sessions to store information about the authenticated users • We will use the key "username" • When it present, there is a logged in user • During the login we will add the user name in the session • Logout will invalidate the session • The main servlet will check the current user
Login Form Login. Form. html <html> <head><title>Login</title></head> <body> <form method="POST" action="Login. Servlet"> Please login: Username: <input type="text" name="username"> Password: <input type="password" name="password"> <input type="submit" value="Login"> </form> </body> </html>
Login Servlet Login. Servlet. java public class Login. Servlet extends Http. Servlet { public void do. Post( Http. Servlet. Request req, Http. Servlet. Response resp) throws IOException, Servlet. Exception { String username = req. get. Parameter("username"); String password = req. get. Parameter("password"); Print. Writer out = resp. get. Writer(); if (is. Login. Valid(username, password)) { Http. Session session = req. get. Session(); session. set. Attribute("USER", username); resp. send. Redirect("Main. Servlet"); } else { resp. send. Redirect("Invalid. Login. html"); } }}
Main Servlet Main. Servlet. java public class Main. Servlet extends Http. Servlet { public void do. Get( Http. Servlet. Request req, Http. Servlet. Response resp) throws Servlet. Exception, IOException { Http. Session session = req. get. Session(); String user. Name = (String) session. get. Attribute("USER"); if (user. Name != null) { resp. set. Content. Type("text/html"); Servlet. Output. Stream out = resp. get. Output. Stream(); out. println("<html><body><h 1>"); out. println("Hello, " + user. Name + "! "); out. println("</h 1></body></html>"); } else { resp. send. Redirect("Login. Form. html"); } } }
Logout Servlet Logout. Servlet. java public class Logout. Servlet extends Http. Servlet { protected void do. Get( Http. Servlet. Request req, Http. Servlet. Response resp) throws Servlet. Exception, IOException { Http. Session session = req. get. Session(); session. invalidate(); resp. set. Content. Type("text/html"); Servlet. Output. Stream out = resp. get. Output. Stream(); out. println("<html><head>"); out. println("<title>Logout</title></head>"); out. println("<body>"); out. println("<h 1>Logout successfull. </h 1>"); out. println("</body></html>"); } }
Invalid Login Page Invalid. Login. html <html> <head> <title>Error</title> </head> <body> <h 1>Invalid login!</h 1> Please <a href="Login. Form. html">try again</a>. </body> </html>
- Slides: 32