Java Learning Notes-sessions (24)

Source: Internet
Author: User

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
    1. A cookie can store only one type of information.
    2. A website can send multiple cookies, and the browser can carry multiple cookies at the same time.
    3. 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.
    4. 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)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.