Presentation is loading. Please wait.

Presentation is loading. Please wait.

Sessions.

Similar presentations


Presentation on theme: "Sessions."— Presentation transcript:

1 Sessions

2 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!??

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

4 Sessions in Servlets Servlets include a built-in Sessions API
Sessions are maintained automatically, with no additional coding The Web container associates a unique HttpSession 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

5 Sessions

6 Sessions Server sends back new unique session ID when the request has
none

7 Sessions Client that supports session stores the ID and sends it
back to the server in subsequent requests

8 Sessions Server knows that all of these requests are from the same
client. The set of requests are known as a session.

9 Sessions And the server knows that all of these requests are
from a different client.

10 Sessions Returns HttpSession object associated with this HTTP request.
Creates new HttpSession object if no session ID in request or no object with this ID exists Otherwise, returns previously created object

11 Sessions Boolean indicating whether returned
object was newly created or already existed. Incremented once per session

12 Sessions Three web pages produced by a single servlet

13 Sessions

14 Sessions Session attribute will have null value until
,,, Session attribute will have null value until a value is assigned Session attribute is a name/value pair

15 Sessions Generate sign-in form if session is new or signIn
,,, Generate sign-in form if session is new or signIn attribute has no value, weclome-back page otherwise.

16 Sessions Sign-in form Welcome-back page

17 Sessions Session attribute methods:
setAttribute(String name, Object value) Creates a session attribute with the given name and value Object getAttribute(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

18 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 setMaxInactiveInterval(int)

19 The Sessions API The sessions API allows
To get the HttpSession object from the HTTPServletRequest 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

20 Getting The Session Object
To get the session object use the method HttpServletRequest.getSession() Example: 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 isNew() method HttpSession session = request.getSession();

21 Behind The Scenes When you call getSession() 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

22 Extracting Data From The Session
* 07/16/96 Extracting Data From The Session The session object works like a HashMap Enables storing any type of Java object Objects are stored by key (like in hash tables) Extracting existing object: Getting a list of all “keys” associated with the session Integer accessCount = (Integer) session.getAttribute("accessCount"); Note: As of Servlet 2.2, the getValue() method is now deprecated. Use getAttribute() instead. Enumeration attributes = request.getAttributeNames(); (c) 2006 National Academy for Software Development -

23 Storing Data In The Session
* 07/16/96 Storing Data In The Session We can store data in the session object for using it later Objects in the session can be removed when not needed more HttpSession session = request.getSession(); session.setAttribute("name", “SE 432"); session.removeAttribute("name"); Note: As of Servlet 2.2, the getValue() method is now deprecated. Use getAttribute() instead. (c) 2006 National Academy for Software Development -

24 Getting Additional Session Information
Getting the unique session ID associated with this user, e.g. gj9xswvw9p Checking if the session was just created Checking when the session was first created Checking when the session was last active public String getId(); public boolean isNew(); public long getCreationTime(); public long getLastAccessedTime();

25 Session Timeout We can get the maximal session validity interval (in seconds) After such interval of inactivity the session is automatically invalidated We can modify the maximal inactivity interval A negative value specifies that the session should never time out public int getMaxInactiveInterval(); public void setMaxInactiveInterval (int seconds);

26 Terminating Sessions To terminate session manually use the method:
Typically done during the "user logout" The session can become invalid not only manually Sessions can expire automatically due to inactivity public void invalidate();

27 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

28 Login Form LoginForm.html <html>
<head><title>Login</title></head> <body> <form method="POST" action="LoginServlet"> Please login:<br> Username: <input type="text" name="username"><br> Password: <input type="password" name="password"><br> <input type="submit" value="Login"> </form> </body> </html>

29 Login Servlet LoginServlet.java
public class LoginServlet extends HttpServlet { public void doPost( HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { String username = req.getParameter("username"); String password = req.getParameter("password"); PrintWriter out = resp.getWriter(); if (isLoginValid(username, password)) { HttpSession session = req.getSession(); session.setAttribute("USER", username); resp.sendRedirect("MainServlet"); } else { resp.sendRedirect("InvalidLogin.html"); } }}

30 Main Servlet MainServlet.java
public class MainServlet extends HttpServlet { public void doGet( HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { HttpSession session = req.getSession(); String userName = (String) session.getAttribute("USER"); if (userName != null) { resp.setContentType("text/html"); ServletOutputStream out = resp.getOutputStream(); out.println("<html><body><h1>"); out.println("Hello, " + userName + "! "); out.println("</h1></body></html>"); } else { resp.sendRedirect("LoginForm.html"); } }

31 Logout Servlet LogoutServlet.java
public class LogoutServlet extends HttpServlet { protected void doGet( HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { HttpSession session = req.getSession(); session.invalidate(); resp.setContentType("text/html"); ServletOutputStream out = resp.getOutputStream(); out.println("<html><head>"); out.println("<title>Logout</title></head>"); out.println("<body>"); out.println("<h1>Logout successfull.</h1>"); out.println("</body></html>"); }

32 Invalid Login Page InvalidLogin.html <html> <head>
<title>Error</title> </head> <body> <h1>Invalid login!</h1> Please <a href="LoginForm.html">try again</a>. </body> </html>


Download ppt "Sessions."

Similar presentations


Ads by Google