Java:cookie implementation Remember user name, password

Source: Internet
Author: User

Tag:stringbu   factory   tty    requires    cookies    div   idt    detailed information    split   

Package Com.gamecenter.api.util;import Java.io.ioexception;import Java.io.printwriter;import Java.io.unsupportedencodingexception;import Java.security.messagedigest;import Java.security.nosuchalgorithmexception;import Javax.servlet.filterchain;import javax.servlet.ServletException; Import Javax.servlet.http.cookie;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Javax.servlet.http.httpsession;import com.gamecenter.api.common.userinfo;/** * Class Description * @author chitu* @version created: November 21, 2016 PM 1:39:51 */public class Cookieut    Il {//cookiename private final static String Cookiedomainname = "Gamecenter" when saving cookies;    Web site custom code when encrypting cookies Private final static String Webkey = "Gamecenter";    Set the cookie to be valid for two weeks, customize private final static long Cookiemaxage = 60 * 60 * 24 * 7 * 2 as required; Save cookies to client-------------------------------------------------------------------------// The user name and password p that were filled in when logged in is encapsulated in the Checklogonservlet.java called//passed in user objectublic static void Savecookie (String username,string password, httpservletresponse response) throws Exception {/           /cookie valid Long validtime = System.currenttimemillis () + (Cookiemaxage * 5000);           MD5 Encrypt user Details String cookieValueWithMd5 =getmd5 (username + ":" + password+ ":" + Validtime + ":" + Webkey);           The full cookie value that will be saved String Cookievalue = Username + ":" + Validtime + ":" + cookieValueWithMd5;           Once again, the value of the cookie is BASE64 encoded as String cookieValueBase64 = new String (Base64util.encode (Cookievalue.getbytes ()));           Start saving Cookie cookie = new Cookie (cookiedomainname, cookieValueBase64);           Save for two years (this value should be greater than or equal to Validtime) cookie.setmaxage (60 * 60 * 24 * 365 * 2);           The valid cookie path is the site root directory Cookie.setpath ("/");    Writes Response.addcookie (cookies) to the client; }//Read the cookie, automatically complete the login operation----------------------------------------------------------------//Call the method in the filter program,See Autologonfilter.java public static void Readcookieandlogon (HttpServletRequest request, httpservletresponse response, Filterchain chain) throws IOException, servletexception,unsupportedencodingexception{//CookieName cookievalue Coo        Kie cookies[] = request.getcookies ();        String cookievalue = null; if (Cookies!=null) {for (int i = 0; i < cookies.length; i++) {if (Cookiedomainname.equals (                           Cookies[i].getname ())) {Cookievalue = Cookies[i].getvalue ();                    Break       }}}//If Cookievalue is empty, return, if (cookievalue==null) {return; }//If Cookievalue is not empty, execute the following code//First get Cookievalue Base64 decode string cookievalueafterdecode = new String (Ba       Se64util.decode (Cookievalue), "Utf-8");       The decoded value is split to get an array, if the array length is not 3, is illegal login String cookievalues[] = Cookievalueafterdecode.split (":");        if (cookievalues.length!=3) {      Response.setcontenttype ("Text/html;charset=utf-8");              PrintWriter out = Response.getwriter ();              Out.println ("You are entering this site in a non-normal way ...");              Out.close ();       Return       }//Decide whether to delete the cookie long Validtimeincookie = new Long (cookievalues[1]) if it expires within the validity period;              if (Validtimeincookie < System.currenttimemillis ()) {//delete cookie ClearCookie (response);              Response.setcontenttype ("Text/html;charset=utf-8");              PrintWriter out = Response.getwriter ();              OUT.PRINTLN ("Your cookie has expired, please re-login");              Out.close ();       Return       }//Remove the user name from the cookie and check the username in the database, String username = cookievalues[0];       Checks whether the user exists Userdao ud = daoimplfactory.getinstance () According to the user name into the database;       User user = Ud.selectuserbyusername (username); If user returns is not empty, remove the password, use username + password + Active time + Websitekey for MD5 encryption if (user!=null) {String Md5valueincookie = Cookieva              LUES[2]; STring Md5valuefromuser =getmd5 (user.getusername () + ":" + user.getpassword () + ":" + Validtimei              Ncookie + ":" + Webkey);                     Compare the result to the MD5 code in the cookie, if the same, write the session, automatically log on successfully, and continue the user request if (md5valuefromuser.equals (Md5valueincookie)) {                     HttpSession session = Request.getsession (true);                     Session.setattribute ("user", user);              Chain.dofilter (request, response);              }}else{//Return Empty execution Response.setcontenttype ("Text/html;charset=utf-8");              PrintWriter out = Response.getwriter (); OUT.PRINTLN ("Cookie validation error!              ");        Out.close ();      Return }///When the user logs off, the cookie is cleared and can be called at any time when needed-----------------------------------------------------public static void ClearCookie (H       Ttpservletresponse response) {Cookie cookie = new Cookie (cookiedomainname, NULL);       Cookie.setmaxage (0);       Cookie.setpath ("/");   Response.addcookie (cookie);}    Gets the MD5 string of the cookie combination string----------------------------------------------------------------public static strings GE              TMD5 (String value) {string result = NULL;                     try{byte[] Valuebyte = Value.getbytes ();                     MessageDigest MD = messagedigest.getinstance ("MD5");                     Md.update (Valuebyte);              result = Tohex (Md.digest ());              } catch (NoSuchAlgorithmException e) {e.printstacktrace ();       } return result; }//Converts the passed-in byte array into a 16-binary string form and returns the private static string Tohex (byte[] buffer) {StringBuffer SB = new              StringBuffer (Buffer.length * 2); for (int i = 0; i < buffer.length; i++) {Sb.append (Character.fordigit (Buffer[i] & 0xf0) &GT;&G T                     4, 16));              Sb.append (Character.fordigit (Buffer[i] & 0x0f, 16));       } return sb.tostring (); }}

  

Java:cookie implementation Remember user name, password

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.