JSP enables automatic website login through Session and Cookie

Source: Internet
Author: User

Step 1: once the [automatic logon] option is selected during login, the following code must be appended after the login is successful. generally, the website provides the function of saving the user name, so I wrote this out. Only passwords are handled separately.
The host is your domain name.
Login. jsp

 

The code is as follows: Copy code
String host = request. getServerName ();
Cookie cookie = new Cookie ("SESSION_LOGIN_USERNAME", username); // save the user name to Cookie
Cookie. setPath ("/");
Cookie. setDomain (host );
Cookie. setMaxAge (99999999 );
Response. addCookie (cookie );
If (ParamUtils. getBooleanParameter (request, "savePassword ")){
// Save the password to the Cookie. Be sure to encrypt it.
Cookie = new Cookie ("SESSION_LOGIN_PASSWORD", MD5.encode (u. getPassword ()));
Cookie. setPath ("/");
Cookie. setDomain (host );
Cookie. setMaxAge (99999999 );
Response. addCookie (cookie );
        }


In this way, the Cookie is generated
Step 2: When the user accesses the website, if the user detects that the user has not logged on, the following judgment will be made.

The code is as follows: Copy code
Index. jsp
String usernameCookie = null;
String passwordCookie = null;
Cookie [] cookies = request. getCookies ();
If (cookies! = Null ){
For (Cookie cookie: cookies ){
If ("SESSION_LOGIN_USERNAME". equals (cookie. getName ())){
UsernameCookie = cookie. getValue (); // Obtain the cookie username
        }
If ("SESSION_LOGIN_PASSWORD". equals (cookie. getName ())){
PasswordCookie = cookie. getValue (); // Obtain the cookie password.
} Www.111cn.net
      }
If (usernameCookie! = Null & passwordCookie! = Null) {// if Yes
If (Login. checkLogin (usernameCookie, passwordCookie )){
// Process successful login
} Else {
// Handle unsuccessful login
        }
      }
    }


Is it easy?

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.