[SpringBoot16] Use Cookie in SpringBoot to remember login

It will be very troublesome to enter the password every time you log in. To implement a function of remembering the login status, we use cookies to realize this function.

1. Introduction to Cookies 

Cookie, a kind of data stored on the user's local terminal, sometimes also uses its plural form Cookies. The type is "small text file", which is the data (usually encrypted) stored on the user's local terminal by some websites in order to identify the user's identity and track the session, and the information is temporarily or permanently saved by the user's client computer.

In fact, a cookie is composed of a key and a value, which is sent to the client browser along with the response from the server. Then the client browser will save the cookie, and send the cookie to the server when it visits the server next time.
 

1. Cookie is one of the specifications of the HTTP protocol. It is small data transmitted between the server and the client.
2. First, the server transmits the Cookie to the client through the response header, and the client will save the Cookie.
3. When the client When requesting the same server again, the client will add the cookie saved by the server to the request header and send it to the server.
4. The cookie is the data saved by the server on the client
. 5. The cookie is a key-value pair
cookie diagram

 

2. Use of cookies 

1. Create cookies 

 // Cookie is a key-value pair data format
Cookie cookie_username = new Cookie("cookie_username", username);

 2. Set the cookie duration

// That is: expiration time, the unit is: seconds (s)
cookie_username.setMaxAge(30 * 24 * 60 * 60); 

3. Set the cookie sharing path 

// Indicates that this cookie is carried under the current project
cookie_username.setPath(request.getContextPath()); 

4. Send Cookie to the client 

// Use the HttpServletResponse object to send Cookie to the client
response.addCookie(cookie_username); 

5. Destroy cookies 

// Empty the value according to the key
Cookie cookie_username = new Cookie("cookie_username", "");
// Set the persistence time to 0
cookie_username.setMaxAge(0);
// Set the shared path
cookie_username.setPath(request.getContextPath() );
// Send Cookie to client
response.addCookie(cookie_username); 

3. Enter the topic 

Above we have understood what a cookie is, and know how to create and destroy a cookie. Next, we will use a cookie to realize the function of remembering the login status. The whole project is implemented based on SpringBoot 

1. Register interceptor 

/**
* 注册拦截器
*/
@Configuration
public class WebConfigurer implements WebMvcConfigurer {

    @Autowired
    private LoginInterceptor loginHandlerInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        InterceptorRegistration ir = registry.addInterceptor(loginHandlerInterceptor);
        // 拦截路径
        ir.addPathPatterns("/*");
        // 不拦截路径
        List<String> irs = new ArrayList<String>();
        irs.add("/api/*");
        irs.add("/wechat/*");
        irs.add("/oauth");
        ir.excludePathPatterns(irs);
    }
}

 We intercepted all request paths, and let go of request paths such as api and wechat

There may be a question here, why not let go of the api request path for requesting the login interface, the reason is that we intercept the login request, when we request the login interface, we have already logged in, then we do not need to enter the login interface, go directly to the main interface

We use a custom login interceptor: LoginInterceptor. In the second step, we will explain the implementation principle in detail
2. Login interception

/**
* 未登录拦截器
*/
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private LoginDao dao;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获得cookie
        Cookie[] cookies = request.getCookies();
        // 没有cookie信息,则重定向到登录界面
        if (null == cookies) {
            response.sendRedirect(request.getContextPath() + "/login");
            return false;
        }
        // 定义cookie_username,用户的一些登录信息,例如:用户名,密码等
        String cookie_username = null;
        // 获取cookie里面的一些用户信息
        for (Cookie item : cookies) {
            if ("cookie_username".equals(item.getName())) {
                cookie_username = item.getValue();
                break;
            }
        }
        // 如果cookie里面没有包含用户的一些登录信息,则重定向到登录界面
        if (StringUtils.isEmpty(cookie_username)) {
            response.sendRedirect(request.getContextPath() + "/login");
            return false;
        }
        // 获取HttpSession对象
        HttpSession session = request.getSession();
        // 获取我们登录后存在session中的用户信息,如果为空,表示session已经过期
        Object obj = session.getAttribute(Const.SYSTEM_USER_SESSION);
        if (null == obj) {
			// 根据用户登录账号获取数据库中的用户信息
        	UserInfo dbUser = dao.getUserInfoByAccount(cookie_username);
            // 将用户保存到session中
            session.setAttribute(Const.SYSTEM_USER_SESSION, dbUser);
        }
        // 已经登录
        return true;
    }
}

 3. Login request

control layer

/**
  * 执行登录
  */
 @PostMapping("login")
 @ResponseBody
 public String login(String username, String password, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
     return service.doLogin(username.trim(), password.trim(), session, request, response).toJSONString();
 }

Business Layer

/**
 * 执行登录
 */
public JSONObject doLogin(String username, String password, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
	// 最终返回的对象
    JSONObject res = new JSONObject();
    res.put("code", 0);
    if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
        res.put("msg", "请输入手机号或密码");
        return res;
    }
    UserInfo dbUser = dao.getUserInfoByAccount(username);
    if (null == dbUser) {
        res.put("msg", "该账号不存在,请检查后重试");
        return res;
    }
    // 验证密码是否正确
    String newPassword = PasswordUtils.getMd5(password, username, dbUser.getSalt());
    if (!newPassword.equals(dbUser.getPassword())) {
        res.put("msg", "手机号或密码错误,请检查后重试");
        return res;
    }
    // 判断账户状态
    if (1 != dbUser.getStatus()) {
        res.put("msg", "该账号已被冻结,请联系管理员");
        return res;
    }
    // 将登录用户信息保存到session中
    session.setAttribute(Const.SYSTEM_USER_SESSION, dbUser);
    // 保存cookie,实现自动登录
    Cookie cookie_username = new Cookie("cookie_username", username);
    // 设置cookie的持久化时间,30天
    cookie_username.setMaxAge(30 * 24 * 60 * 60);
    // 设置为当前项目下都携带这个cookie
    cookie_username.setPath(request.getContextPath());
    // 向客户端发送cookie
    response.addCookie(cookie_username);
    res.put("code", 1);
    res.put("msg", "登录成功");
    return res;
}

4. Logout and login

/**
 * 退出登录
 */
@RequestMapping(value = "logout")
public String logout(HttpSession session, HttpServletRequest request, HttpServletResponse response) {
    // 删除session里面的用户信息
    session.removeAttribute(Const.SYSTEM_USER_SESSION);
    // 保存cookie,实现自动登录
    Cookie cookie_username = new Cookie("cookie_username", "");
    // 设置cookie的持久化时间,0
    cookie_username.setMaxAge(0);
    // 设置为当前项目下都携带这个cookie
    cookie_username.setPath(request.getContextPath());
    // 向客户端发送cookie
    response.addCookie(cookie_username);
    return "login";
}

 When logging out, we need to delete the user information in the session, delete the user information in the cookie, and then request to the login interface

Four. Summary

The above is the use of Cookie in SpringBoot to realize the function of remembering login. It is a relatively practical function in the project. I hope it can help and inspire you who are reading

Guess you like

Origin blog.csdn.net/wufaqidong1/article/details/129675560