08
-
Many Web Applications have “State”
They can “remember” me between repeated requests. Sometimes over a longer period of time (although for security reasons that may be problematic, more about that next week).
- But the http Protocol is Stateless
- Everything that is needed for a server to respond to a request is included in the request itself.
- Therefore the server doesn’t need to remember the user.
- Request an html page
- The Hyper Text Transfer Protocol (http) is the client-server network protocol that has been in use by the World-Wide Web since 1990.
- When an html page is viewed, the browser sends an HTTP request for the page and it's images, scripts, styles sheets and other resources.
- Web servers handle these requests by returning a response message that contains the requested resource if the request is successful.
-
Http is a Stateless Protocol
Activity: Examine the http communication of any web page: More Tools -> Developer Tools -> Network -> All -> Click on a resource -> view Headers- Benefits of a Stateless Protocol
- Requests are more complicated, as they contain everything needed to fulfil the request but it simplifies the protocol as there is no need to sync session state between client and server.
- Applications scale better as different servers can handle requests for one application.
- For the client:
- Can access resources directly without having to go through previous states.
- For the server:
- Eliminates failure conditions that may result from servers having to keep track of request sequences.
- The client never times out.
- Server never loses track where client is in application because client sends all necessary information with each request.
- Pages are easier to cache.
- Sometimes statelessness is not enough
- We want to be able to distinguish the requests from a particular user from all the other requests coming in to the server
- Example:
- This particular user is already logged in
- The server needs to know that a particular request comes from a user.
-
Method: A Session
- The term user session refers to a series of user application interactions that are tracked by the server.
- Sessions are used for maintaining user specific state, including persistent objects (such as handles to database result sets) and authenticated user identities, among many interactions.
- Track a validated user login followed by a series of directed activities for a particular user.
- The session resides in the server.
- For each request, the client transmits the session ID in a cookie or, if the browser does not allow cookies, the server automatically writes the session ID into the URL.
- Practically there is a Session object.
-
Java Session Management (Session Tracking)
- Session - a "single continuous sitting" [dictionary.com].
- In the context of web applications a session consists of multiple request and response between client and server.
- A session is maintained when some unique information about the session (session id) is passed between server and client in every request and response.
-
Popular Methods of Implementing Sessions in Java
- Cookies (used in the examples here).
A cookie is data sent by a web server in the response to a browser. When a browser receives a response with a cookie, it stores the cookie in the browser and includes the cookie in subsequent requests to the same server. Cookies are name = value pairs, the cookie’s value can uniquely identify a client and are so often used for session tracking. - Session Management API (used in the examples here).
The Servlet API provides several methods and classes for the purpose of session handling, i.e. servlets have built in session tracking. - URL re-writing
Every local URL the user might click on is dynamically modified, or rewritten, to include extra information by appending a session identifier parameter to every request (and response) to keep track of the session and ensure there are no conflicts with other parameters. As URLs are easily cached in browsers that is not a very secure method. - User Authentication
- Does not support one user is logged in from different browsers.
- HTML Hidden Field
- Requires a form to be submitted every time request is made from client to server. The form contains a hidden field with user identification.
- This method is not secure because users can access the hidden field value from the HTML source and use it to hack the session.
- Cookies
- Sessions can be maintained by sending the value of JSESSIONID as a query parameter
- Example: Using http GET request with session id
🔗 http://www.site.com/somePage?JSESSIONID=123456789012
It is more secure to send the session id over http POST in the body of the request (more about that next week). - NB: Cookies can be disabled by the browser, they can’t be guaranteed.
- Cookies (used in the examples here).
-
Explicitly Setting a Cookie on the Server
Cookies are typically set on the server (but can be set on the client using JavaScript).
The example below generates a cookie and attaches it to the response.
if (authenticated) { Cookie loginCookie = new Cookie("user",user); //setting cookie to expiry in 30 mins loginCookie.setMaxAge(30*60); response.addCookie(loginCookie); response.sendRedirect("LoginSuccess.jsp"); }else{ RequestDispatcher rd = getServletContext().getRequestDispatcher("/login.html"); PrintWriter out= response.getWriter(); out.println("<font color=red>Either user name or password is wrong.</font>"); rd.include(request, response); }
-
Session Management API
- Enabling Sessions
- In Java Sessions are enabled by setting ServletContextHandler.SESSIONS
- In the lab examples this is implemented in Runner.java:
ServletContextHandler handler = new ServletContextHandler(server, "/",
ServletContextHandler.SESSIONS); - Now cookies are sent back and forth with every request/response.
- These can be examined in the browser.
- Typical Java Classes for Sessions
- The HttpServletRequest interface provides two methods to get an object of HttpSession:
- public HttpSession getSession()
- Returns the current session associated with this request, or if the request does not have a session, creates one.
- public HttpSession getSession(boolean create)
- Returns the current HttpSession associated with this request or, if there is no current session and create is true, returns a new session.
- Typical Java Methods for Sessions
- public String getId():Returns a string containing the unique identifier value.
- public long getCreationTime():Returns the time when this session was created, measured in milliseconds since midnight January 1, 1970 GMT.
- public long getLastAccessedTime():Returns the last time the client sent a request associated with this session, as the number of milliseconds since midnight January 1, 1970 GMT.
- public void invalidate():Invalidates this session then unbinds any objects bound to it.
- setAttribute() for setting session attributes
- getAttribute() for getting session attributes
Writing to a Session Object
HttpSession session=request.getSession(true); session.setAttribute("uname",n);
Reading from a Session Object
HttpSession session = request.getSession(false); String n = (String) session.getAttribute("uname");
- The Session Life Cycle
- Sessions do not last forever. A session either expires automatically, after a set time of inactivity (either by reaching the default time period on the server or the explicitly let life time) or can be explicitly revoked by a servlet.
- When a session expires (or is invalidated), the HttpSession object and the data values it removed from the system.
- Use the invalidate() method on the Session object to revoke a session.
session.invalidate()