More About ServletsPersistent informationServer capabilitiesSession trackingSession tracking solutionsHidden <form> fieldsCookiesUsing cookiesSome more Cookie methodsMore HttpServletRequest methodsThe Session Tracking APISummaryThe EndJan 13, 2019More About ServletsSession TrackingPersistent informationA server site typically needs to maintain two kinds of persistent (remembered) information:Information about the sessionA session starts when the user logs in or otherwise identifies himself/herself, and continues until the user logs out or completes the transaction (for example, makes a purchase)Information about the userUser information must generally be maintained much longer than session information (for example, remembering a purchase)This information must be stored on the server, for example on a file or in a databaseServer capabilitiesServlets, like Applets, can be trusted or untrustedA servlet can use a unique ID to store and retrieve information about a given sessionUser information usually requires a login ID and a passwordSince servlets don’t quit between requests, any servlet can maintain information in its internal data structures, as long as the server keeps runningA trusted servlet can read and write files on the server, hence can maintain information about sessions and users even when the server is stopped and restartedAn untrusted servlet will lose all information when the servlet or server stops for any reasonThis is sometimes good enough for session informationThis is almost never good enough for user informationSession trackingHTTP is stateless: When it gets a page request, it has no memory of any previous requests from the same clientThis makes it difficult to hold a “conversation”Typical example: Putting things one at a time into a shopping cart, then checking out--each page request must somehow be associated with previous requestsThe server must be able to keep track of multiple conversations with multiple usersSession tracking is keeping track of what has gone before in this particular conversationSince HTTP is stateless, it does not do this for youYou have to do it yourself, in your servletsSession tracking solutionsCookies are small files that the servlet can store on the client computer, and retrieve laterURL rewriting: You can append a unique ID after the URL to identify the userHidden <form> fields can be used to store a unique IDJava’s Session Tracking API can be used to do most of the work for youHidden <form> fields<input type="hidden"name="sessionID"value="...">Advantage:Requires the least knowledge: All you need to know is how to read and write parametersDisadvantages:Not kept across sessions, so useless for maintaining persistent information about a userSince the session ID must be incorporated into every HTML page, every HTML page must be dynamically generatedThere’s not much more to say about using hidden form fields, since you should already know enough to do itCookiesA cookie is a small bit of text sent to the client that can be read again laterLimitations (for the protection of the client):Not more than 4KB per cookie (more than enough in general)Not more than 20 cookies per siteNot more than 300 cookies totalCookies are not a security threatCookies can be a privacy threat Cookies can be used to customize advertisementsOutlook Express allows cookies to be embedded in emailA servlet can read your cookiesIncompetent companies might keep your credit card info in a cookieNetscape lets you refuse cookies to sites other than that to which you connectedUsing cookiesimport javax.servlet.http.*;Constructor: Cookie(String name, String value)Assuming request is an HttpServletRequest and response is an HttpServletResponse,response.addCookie(cookie);Cookie[ ] cookies = request.getCookies();String name = cookies[i].getName();String value = cookies[i].getValue();There are, of course, many more methods in the HttpServletRequest, HttpServletResponse, andCookie classes in the javax.servlet.http packageSome more Cookie methodspublic void setComment(Stringpurpose)public String getComment()public void setMaxAge(intexpiry)public int getMaxAge()Max age in seconds after which cookie will expireIf expiry is negative, delete when browser exitsIf expiry is zero, delete cookie immediatelysetSecure(booleanflag )public boolean getSecure()Indicates to the browser whether the cookie should only be sent using a secure protocol, such as HTTPS or SSLMore HttpServletRequest methodspublic HttpSession getSession()Gets the session object for this request (or creates one if necessary)public Enumeration getHeaderNames()Gets an Enumeration of all the field names in the HTTP headerpublic String getHeader(Stringname)Given the header name, return its valuepublic int getIntHeader(Stringname)Given the header name, return its value as an intReturns -1 if no such headerCould throw a NumberFormatExceptionpublic Enumeration getHeaders(Stringnam e)Given the header name, return an Enumeration of all its valuesThe Session Tracking APIThe session tracking API is in javax.servlet.http.HttpSession and is built on top of cookiesTo use the session tracking API:Create a session:HttpSession session = r equest.getSession();Returns the session associated with this requestIf there was no associated session, one is createdStore information in the session and retrieve it as needed:session.setAttribute(name, value);Object obj = getAttribute(nam e);Session information is automatically maintained across requestsSummaryA session is a continuous interaction with the userHTTP is stateless, so the programmer must do something to remember session informationThere are multiple ways to remember session informationThe session ends when the user quits the browser (or a session may be set to time out)Some information must be kept longer than just within a sessionFor example, if the user orders a product, that information must be kept in a databaseLong-term storage of information requires that the servlet have some additional privilegesThe
View Full Document