Sessions in Web Development

sessions n.w
1 / 32
Embed
Share

Learn about sessions in web development, how they help maintain user state, and how servers manage session data for a seamless user experience. Explore the importance of sessions in creating personalized applications and handling user preferences.

  • Web Development
  • Sessions
  • User Data
  • Server Management
  • State Persistence

Uploaded on | 1 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

You are allowed to download the files provided on this website for personal or commercial use, subject to the condition that they are used lawfully. All files are the property of their respective owners.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.

E N D

Presentation Transcript


  1. Sessions

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

  3. What is a Session? 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 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 Sessions

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

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

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

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

  10. Sessions 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 Sessions Boolean indicating whether returned object was newly created or already existed. Incremented once per session

  12. Sessions Sessions Three web pages produced by a single servlet

  13. Sessions Sessions 13

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

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

  16. Sessions Sessions Sign-in form Welcome-back page

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

  21. Behind Behind T The Scenes he 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 Extracting Data From The The Session 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: Integer accessCount = (Integer) session.getAttribute("accessCount"); Getting a list of all keys associated with the session Enumeration attributes = request.getAttributeNames();

  23. Storing Storing Data Data In In The The Session Session We can store data in the session object for using it later HttpSession session = request.getSession(); session.setAttribute("name", SE 432"); Objects in the session can be removed when not needed more session.removeAttribute("name");

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

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

  26. Terminating Sessions 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

  27. Login / Logout Login / Logout Example 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 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 Login Servlet LoginServlet.java public class LoginServlet extends HttpServlet { public void doPost( 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"); } }} HttpServletRequest req, HttpServletResponse resp)

  30. Main Servlet Main Servlet MainServlet.java public class MainServlet extends HttpServlet { public void doGet( 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"); } } } HttpServletRequest req, HttpServletResponse resp)

  31. Logout Servlet 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 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>

More Related Content