1 using cookies to display the last access time for a user
Public voiddoget (httpservletrequest request, httpservletresponse response) throws Servletexception, IOException {//page OutputResponse.setcharacterencoding ("Utf-8"); Response.setcontenttype ("Text/html;charset=utf-8"); Request.setcharacterencoding ("Utf-8"); //get character output stream objectPrintWriter out=Response.getwriter (); //Get cookie Array ObjectCookies [] cookies =request.getcookies (); //defining a time-of-day string variableString date =NULL; //define a variable storage system current dateDate current_date =NewDate (); SimpleDateFormat format=NewSimpleDateFormat ("YYYY-MM-DD Hh:mm:ss"); //determine if it is the first time to log in if(Cookies! =NULL){ //Direct Loop for(Cookie cookie:cookies) {//Get Cookies if("Lasttime". Equals (Cookie.getname ())) { //gets the last access timeDate =Cookie.getvalue (); Break; }Else{ //Get system TimeDate =Format.format (current_date); } } }Else{ //Get system TimeDate =Format.format (current_date); } //Show Time out. println (date); //write the time of this visit to a cookieCookie New_cookie =NewCookies ("Lasttime", Format.format (NewDate ())); New_cookie.setmaxage (5* -); New_cookie.setpath ("/day08/showtime"); //SendResponse.addcookie (New_cookie); }
Cookie Details
- A cookie can store only one type of information.
- A website can send multiple cookies, and the browser can carry multiple cookies at the same time.
- A maximum of 20 cookies are sent to the same website, the browser stores up to 300 cookies, and a cookie stores data up to 4K.
- If you create a cookie object that does not specify a maximum effective time, it is not stored in the browser's cache.
Session Technology
When using cookie technology to store session information, it is found that cookies store limited data, and each time a client browser is required to carry data, the load on the network is too large. Therefore, if you need to store relatively large amounts of data, you can store the data directly on the server side, which can improve the speed of data access.
HttpSession technology is to store the session's data on the server side, which makes it easy for developers to access it directly.
1 HttpSession interface
This interface primarily defines a way to distinguish between different users and to obtain an instance of the object by using the request object to store information related to the user.
The object of the interface is created by the Tomcat server to help the developer, when the developer calls the Request.getsession () method to get the object of the interface.
2 Common APIs
Get HttpSession Object
HttpSession getsession () ? If there is a direct return, if it is not created directly and returns HttpSession GetSession (Boolean create) ? True Ditto, False has a return, No null
Manipulating data
void SetAttribute (String name, Object value) ? Sets the property value of the specified name Object getattribute (String name) ? Gets the property value of the specified name enumeration getattributenames () ? Gets the collection iterator for all property names void removeattribute (String name) ? Delete the property of the specified name
Additional methods
String getId () ? Gets the ID value of the session, Boolean isnew () ? Determine if the session is a new long getcreationtime () ? Gets a long of session creation time Long getlastaccessedtime () ? Gets the time of the last access session void invalidate () ? Invalid session specified
3 reading and writing of HttpSession
1. Write Session data
Public void doget (httpservletrequest request, httpservletresponse response) throws Servletexception, IOException { // get Session Object HttpSession session = request.getsession (); // Placing Data Session.setattribute ("name""Jack");
Find the response information in set-cookie:jsessionid=8aa06cd311ec6a38805c73c93b8fce4f; The PATH=/DAY08 response header data sends the ID value of the HttpSession object to the browser for storage by way of a cookie.
2. Read session data
public void Doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { // get Session object HttpSession session = req Uest.getsession (); // fetch session data String name = (Strin g) Session.getattribute ( name " ); // output information System.out .println (name);}
The ID value of the HttpSession object is carried in the request message using COOKIE:JSESSIONID=8AA06CD311EC6A38805C73C93B8FCE4F. The server then finds the corresponding HttpSession object based on that value to get its value.
Summarize:
HttpSession Technology The bottom-up requires the use of cookies to store the ID value of the HttpSession object created by the server for each user, so that you can get the value from the server-specified object later.
3 re-examine the above code
The code that gets sessiond in the servlet that gets the data can be modified as follows
HttpSession session = Request.getsession (false);
Now that the actual browser launches multiple browser windows, the same session object is used automatically. Once the session is valid for more than half an hour, the session is automatically destroyed.
4 Other common methods
Public voiddoget (httpservletrequest request, httpservletresponse response) throws Servletexception, IOException {//Get Session ObjectHttpSession session =request.getsession (); //calling a common methodSystem. out. println ("getId ():"+Session.getid ()); System. out. println ("getlastaccessedtime ():"+session.getlastaccessedtime ()); System. out. println ("isnew ():"+session.isnew ()); System. out. println ("getcreationtime ():"+session.getcreationtime ());}
Run results
1358385915203true1358385915203
If you use Session.invalidate () in the above code, and then continue to add data to the session, the server error
Java.lang.IllegalStateException:setAttribute:Session already invalidated
Summarize:
Login function Analysis À1. Get user Data 2. Checksum Data 3. Successful, storing the user's login ID in session
Logoff function Analysis À1. Clears the user ID information in session 2. Redirect to landing page
Java Learning Notes-sessions (24)