cookie remembering account password function in Java Web Technology (permanent login)

Keywords: Java cookie mvc

preface

When I was working on a Java Web project, I encountered the need to remember the account and password, but I didn't do it before. I only did c#. Net MVC to remember the account. Suddenly I didn't know how to start, and then I went to the Internet to find information. However, my understanding ability may not be very good, so I didn't understand it very well. Then I looked back at the code made using c#. Net MVC technology, After a while, it was finally done, but I didn't expect to publish a blog at that time. Until now, this function is encountered in the project, so it is published immediately for your reference. If there is anything wrong, please give me more advice.

1, What is a cookie

Cookie, which means "cookie", is a mechanism proposed by W3C and first developed by Netscape community. At present, cookies have become the standard, and all mainstream browsers such as IE, Netscape, Firefox, Opera, etc. support cookies.

Because HTTP is a stateless protocol, the server cannot know the identity of the client from the network connection alone. What shall I do? Just issue a pass to the clients, one for each person. No matter who visits, they must carry their own pass. In this way, the server can confirm the customer's identity from the pass. This is how cookies work.

A Cookie is actually a short piece of text information. The client requests the server. If the server needs to record the user status, it uses response to issue a Cookie to the client browser. The client browser saves the Cookie. When the browser requests the website again, the browser submits the requested URL to the server together with the Cookie. The server checks the Cookie to identify the user status. The server can also modify the contents of the Cookie as needed.

2, Java Web case: remember account and password (permanent login)

On this basis, you first need to complete the normal login function. Here we will only explain the code part about remembering the account and password,

To remember the password first, you need to layout a check box on the page. The checked casual cloth I use here comes with layui

jsp page code:
The submission here still uses layui to listen for submission. Because it is simple and convenient, this is not the point.

The key point is the variable isOk. Because I use the built-in of layui, I can't get the value of the check box input=checked, that is, whether to check it or not. Therefore, I define a variable in js and listen for the click of the check box at the same time

 var isOk = true;//Whether to remember the account password (true: remember, false: don't remember)

 //Listen check box
 form.on('checkbox(filter)', function (data) {
      isOk = data.elem.checked;
  });


//Listen to submit login
form.on('submit(formDemo)', function (data) {
//Because the checked field is not added, it needs to be added manually
data.field = {
    identity: data.field.identity,
    password: data.field.password,
    userAccount: data.field.userAccount,
    isOk: isOk
};

$.post("${ctx}/login/doLogin", data.field, function (jsonData) {
    if (jsonData.state) {
        window.location.replace("${ctx}/home");//Jump to main page
    } else {
        layer.alert(jsonData.msg, {icon: 5});
    }
});

return false;
});

Split line ============================================================

Then, in the Controller (that is, Servlet) layer, cookie s need to be used in the login authentication method

  //Create a cookie
  Cookie cookie = new Cookie("cookie_user",userAccount + "-" + password);
  if(isOk){   //Judge whether to check remember account password
        //Checked
        //Set the expiration time to seven days, in minutes
        cookie.setMaxAge(60*60*24*7);
        //Return the cookie through the response and tell the browser to process the cookie
        response.addCookie(cookie);
    }else {
        //Uncheck delete user's cookie (in fact, set the storage time to 0)
        cookie.setMaxAge(0); //Set cookie expiration time to 0
        response.addCookie(cookie);
    }

Then write an additional method to get the account and password from cookiezz in the Controller

@RequestMapping("/backfill")
@ResponseBody
public JsonMsg backfill(HttpServletRequest request) {
    JsonMsg jsonMsg = new JsonMsg();//This entity class is used to return json data format
    Cookie[] cookie =  request.getCookies();

    //The data here may be null (that is, unchecked), so it is not judged
    jsonMsg.setData(cookie);

    return jsonMsg;
}

Code in JSON entity class

package com.gx.vo;

import java.io.Serializable;

/**
 * Return message class
 * It is mainly compatible with the return type of layui
 */
public class JsonMsg implements Serializable{
	/**
	 * 
	 */
	private static final long serialVersionUID = 5863100019332084445L;

	private Boolean state;//state
	private int code;
	private String msg;//news
	private Object data;

	public Boolean getState() {
		return state;
	}

	public void setState(Boolean state) {
		this.state = state;
	}

	public int getCode() {
		return code;
	}

	public void setCode(int code) {
		this.code = code;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public Object getData() {
		return data;
	}

	public void setData(Object data) {
		this.data = data;
	}
}

Finally, write the js code of the cookie method in the page loading event in jsp
Request the background method, select the text box of account and password, and backfill the data.

//Page load event
$(function (){
	//Get the account and password in the cookie
	$.post('${ctx}/login/backfill', function (jsonData) {
	     for (var x in jsonData.data) {
	         if (jsonData.data[x].name == "cookie_user") {
	             var value = jsonData.data[x].value;//get data
	
	             //It is reasonable to judge whether there is data before segmentation, but it may not be checked. Remember, so the data may be empty and can be backfilled directly
	             var arr = value.split("-");//Split character
	             //Automatic backfill data
	             $('input[name="userAccount"]').val(arr[0]);    //account number
	             $('input[name="password"]').val(arr[1]);    //password
	         }
	     }
	 });     
})

ps

Because of my expressive ability, you may not understand it very well, but in fact, there are only a few sentences in the core code, that is, the use of cookie s in the background, so you can watch it according to your own needs or read it patiently and slowly. If there is any mistake, please give me more advice.

Posted by almightyad on Mon, 20 Sep 2021 10:14:10 -0700