Java uses cookies to record the user's last access time remember the user's login name

Source: Internet
Author: User
Tags browser cache

Package Cn.itcast.cookie;import;import;import java.util.Date;import Javax.servlet.servletexception;import Javax.servlet.http.cookie;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import javax.servlet.http.httpservletresponse;// Remember the last time a user visited: Lastaccesstime=23432432432public class CookieDemo1 extends HttpServlet {public void doget (httpservletre Quest request, HttpServletResponse response) throws Servletexception, IOException {Response.setcontentt Ype ("Text/html;charset=utf-8"); PrintWriter out = Response.getwriter (); Take the value of the specified cookie LastAccessTime to print to the page out.write ("The time you last visited is:"); Cookie cs[] = request.getcookies (); if (Cs!=null) {for (int i=0;cs!=null&&i<cs.length;i++) {Cookie c = cs[i]; if ("LastAccessTime". Equals (C.getname ())) {String value = C.getvalue (); Long Time = Long.parselong (value); Out.print (New Date) tolocalestring ()); }}} else {Out.write ("This is the first time you've visited! "); }//write back the time of the current visit cookie C = new Cookie ("LastAccessTime", System.currenttimemillis () + ""); /* Set the maximum time for the cookie to be saved, that is, when the server sends a cookie back to the browser, if the Setmaxage method is not set on the server side, the cookie's validity period is only In a session, the user open a browser, click multiple hyperlinks, access the server multiple Web resources, and then close the browser, the entire process is called a session, when the user closes the browser, the session is over, the cookie will expire, if the server side using the Setmaxage method Set the validity period of the cookie, for example, set for 30 minutes, then when the server sends the cookie to the browser, the cookie is stored on the client's hard disk for 30 minutes, and in 30 minutes, even if the browser is off, the cookie still exists, and in 3 In 0 minutes, when you open the browser to access the server, the browser will bring the cookie together, so that the server can get to the client browser passed the cookie information, which is the cookie settings maxage and do not set the difference between MaxAge, do not set MAXAG E, then the cookie is only valid in one session, once the user closes the browser, then the cookie is gone, then how does the browser do it, we start a browser, it is equivalent to launch an application, and the server loopback of the cookie is the presence of the browser cache , when the browser is closed, the browser's cache is naturally gone, so the cookie stored in the cache is naturally cleared, and if the cookie is set to expire, theWhen the browser is closed, the cookie in the cache is written to the hard disk and stored so that the cookie can persist. * * */c.setmaxage (30*24*60*60);//Integer.max_value C.setpath (Request.getcontextpath ());//C.setpath ( "/day07"); The cookie object is added to the response object so that the server outputs the contents of the response object to the client browser Response.addcookie (c); Empty Out.write ("<a href= '/day07/servlet/cookiedemo2 ' >clear</a>"); } public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, Ioex ception {doget (request, response); }}

Access the above servlet, as shown below.

Click Clear to access the following servlet to clear the cookie

1  2 3  PackageCn.itcast.cookie;4 5;6 7 Importjavax.servlet.ServletException;8 ImportJavax.servlet.http.Cookie;9 ImportJavax.servlet.http.HttpServlet;Ten Importjavax.servlet.http.HttpServletRequest; One ImportJavax.servlet.http.HttpServletResponse; A //empty the specified cookie -  Public classCookieDemo2extendsHttpServlet { -  the      Public voiddoget (httpservletrequest request, httpservletresponse response) -             throwsservletexception, IOException { -Cookie C =NewCookie ("LastAccessTime", "" "); -C.setmaxage (0); +         /* - * SetPath () + * Set the valid path of the cookie, such as setting the valid path of the cookie to "/XDP", then when the browser accesses the Web resource under the "XDP" directory , A * will bring a cookie, such as the effective path of the cookie is set to "/xdp/gacl", at * Then the browser will only be accessed with a cookie when accessing the Web resources in the directory "GaCl" under the "XDP" directory . - * When accessing Web resources under the "XDP" directory, the browser is not a cookie -          * -          * */ - C.setpath (Request.getcontextpath ()); - Response.addcookie (c); in         //Set Refresh response header to allow the browser to jump to/day07/servlet/cookiedemo1 after 3 seconds -Response.setheader ("Refresh", "3; Url=/day07/servlet/cookiedemo1 "); to     } +  -      Public voidDoPost (httpservletrequest request, httpservletresponse response) the             throwsservletexception, IOException { *  $ doget (request, response);Panax Notoginseng     } -  the}

When the user logs in, by ticking, save the user name, the next time the user entered the site login, no longer enter the user name.

public void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {// Read the remembered user name string username = ""; String checked = "";//cookie cs[] = request.getcookies (); for (int i=0;cs!=null&&i<cs.length;i++) {//user logon for the first time, Cs==nullcookie C = cs[i];//parsing, the client brings over the cookie, takes out, and saves the user name in the cookie. if ("UserInfo". Equals (C.getname ())) {String value = C.getvalue ();//user name username = value;checked = "checked= ' checked '"; Break;}} Provide login interface Response.setcontenttype ("Text/html;charset=utf-8"); PrintWriter out = Response.getwriter (); Out.write ("<form action= '/day07/servlet/loginservlet ' method= ' post ' >") ;//test, user name first do not use Chinese out.write ("User name: <input type= ' text ' name= ' username ' value= '" +username+ ""/><br/> ");// Populate the user name stored in the cookie with the login user name box Out.write ("Password: <input type= ' password ' name= ' password ' value= '); o Ut.write ("<input type= ' checkbox ' name= ' Remember '" +checked+ "/> Remember user name <br/>"); Out.write ("<input type=" Submit ' value= ' login '/> '); Out.write ("</form> ");} 

Complete Login//According to whether you need to remember the username to write Cookiepublic class Loginservlet extends HttpServlet {public void doget (HttpServletRequest request , httpservletresponse response) throws Servletexception, IOException {response.setcontenttype ("text/html;charset= UTF-8 "); PrintWriter out = Response.getwriter (); String username = request.getparameter ("username"); String Password = request.getparameter ("password"); String remember = Request.getparameter ("Remember");//verify the username and password user username = userdb.finduser (username, password); if (user= =null) {out.write ("wrong user name or password"); return;} Processing cookies:  userinfo=gfycookie c = new Cookie ("UserInfo", username);//The path of user name, write cookie, save to browser side, user next visit again. will be saved in the browser-side cookie and brought together. C.setpath (Request.getcontextpath ()); if (remember==null) {//delete cookiec.setmaxage (0);} else{//remember Cookiec.setmaxage (Integer.max_value);} Response.addcookie (c); Out.print ("Congratulations! Login successful ");}

Java uses cookies to record the user's last access time remember the user's login name

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: 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.