SpringBoot中使用Cookie实现记住登录

一、Cookie简介

Cookie一种储存在用户本地终端上的数据,有时也用其复数形式Cookies。类型为“小型文本文件“,是某些网站为了辨别用户身份,进行 Session 跟踪而储存在用户本地终端上的数据(通常经过加密),由用户客户端计算机暂时或永久保存的信息。

其实 Cookie 就是一个键和一个值构成的,随着服务器端的响应发送给 客户端 浏览器。然后客户端浏览器会把 Cookie 保存起来,当下一次再访问服务器时把 Cookie 再发送给服务器。

1、Cookie 是 HTTP 协议的规范之一,它是服务器和客户端之间传输的小数据

2、首先由服务器通过响应头把 Cookie 传输给客户端,客户端会将 Cookie 保存起来

3、当客户端再次请求同一服务器时,客户端会在请求头中添加该服务器保存的 Cookie,发送给服务器

4、Cookie 就是服务器保存在客户端的数据

5、Cookie 就是一个键值对

二、Cookie 使用

1、创建 Cookie
// Cookie 为键值对数据格式
Cookie cookie_username = new Cookie("cookie_username", username);
2、设置 Cookie 持久时间
// 即:过期时间,单位是:秒(s)
cookie_username.setMaxAge(30 * 24 * 60 * 60);  // 设置cookie的持久化时间,30天
3、设置 Cookie 共享路径
// 表示当前项目下都携带这个cookie
cookie_username.setPath(request.getContextPath());
4、向客户端发送 Cookie
// 使用 HttpServletResponse 对象向客户端发送 Cookie
response.addCookie(cookie_username);
5、销毁 Cookie
// 根据 key 将 value 置空
Cookie cookie_username = new Cookie("cookie_username", "");
// 设置持久时间为0
cookie_username.setMaxAge(0);
// 设置共享路径
cookie_username.setPath(request.getContextPath());
// 向客户端发送 Cookie
response.addCookie(cookie_username);

三、进入正题

上面我们已经了解了 Cookie 是什么,并且知道了 Cookie 的创建以及销毁的方法,下面,我们就使用 Cookie 实现记住登录状态的功能,整个项目基于 SpringBoot 实现

1、引入依赖、创建启动类、常量类
<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.7.18</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.32</version>
        </dependency>
    </dependencies>
@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}
public interface Const {
    String SYSTEM_USER_SESSION = "system_user_session";
}
2、注册拦截器

我们拦截了所有的请求路径,放开了 login、logout 等请求路径。

我们使用了自定义的一个登录拦截:LoginInterceptor

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.ArrayList;
import java.util.List;

/**
* 注册拦截器
*/
@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<>();
        irs.add("/**/login");
        irs.add("/**/logout");
        ir.excludePathPatterns(irs);
    }
}
3、对非登录请求,进行拦截
import com.sc.bean.UserInfo;
import com.sc.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获得cookie
        Cookie[] cookies = request.getCookies();
        // 没有cookie信息,则重定向到登录界面
        if (null == cookies) {
            log.info("cookies为空,重定向至登陆界面");
            return false;
        }
        // 获取cookie里面的一些用户信息
        String username = null;
        for (Cookie item : cookies) {
            if ("cookie_username".equals(item.getName())) {
                username = item.getValue();
                break;
            }
        }
        // 如果cookie里面没有包含用户的一些登录信息,则重定向到登录界面
        if (StringUtils.isEmpty(username)) {
            log.info("cookie没有用户信息,重定向至登陆界面");
            return false;
        }
        // 获取HttpSession对象
        HttpSession session = request.getSession();
        // 获取我们登录后存在session中的用户信息,如果为空,表示session已经过期
        UserInfo userInfo = (UserInfo) session.getAttribute(Const.SYSTEM_USER_SESSION);
        if (null == userInfo) {
			// 根据用户登录账号获取数据库中的用户信息
        	UserInfo dbUser = userService.getUserInfoByAccount(username);
            if (dbUser==null){
                log.info("没查到用户信息,重定向至登陆界面");
                return false;
            }
            // 将用户保存到session中
            session.setAttribute(Const.SYSTEM_USER_SESSION, dbUser);
        }
        // 已经登录
        return true;
    }
}
4、登录、登出、访问首页

注销登录时,我们需要删除 session 里面的用户信息,删除 cookie 里面的用户信息

import com.sc.config.Const;
import com.sc.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("/demo")
public class LoginController {

    @Autowired
    LoginService loginService;


    @GetMapping("/index")
    public String index()
    {
        return "访问首页成功";
    }

    /**
     * 执行登录
     */
    @PostMapping("/login")
    public Map<String, Object> login(String username, String password, HttpSession session, HttpServletRequest request, HttpServletResponse response)
    {
        return loginService.doLogin(username.trim(), password.trim(), session, request, response);
    }

    /**
     * 登出
     */
    @GetMapping(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 "登出成功";
    }

}
import com.sc.bean.UserInfo;
import com.sc.config.Const;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.LinkedHashMap;
import java.util.Map;

@Service
public class LoginService {

    @Autowired UserService userService;

    /**
     * 执行登录
     */
    public Map<String,Object> doLogin(String username,
                              String password,
                              HttpSession session,
                              HttpServletRequest request,
                              HttpServletResponse response)
    {
        // 最终返回的对象
        Map<String,Object> res = new LinkedHashMap<>();
        res.put("code", 0);
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            res.put("msg", "请输入手机号或密码");
            return res;
        }
        UserInfo dbUser = userService.getUserInfoByAccount(username);
        if (null == dbUser) {
            res.put("msg", "该账号不存在,请检查后重试");
            return res;
        }
        // 验证密码是否正确
        if (!password.equals(dbUser.getPassword())) {
            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;
    }
}
import com.sc.bean.UserInfo;
import org.springframework.stereotype.Service;

@Service
public class UserService {

    public UserInfo getUserInfoByAccount(String userName){
        UserInfo userInfo = new UserInfo();
        userInfo.setUserName("xiaomi");
        userInfo.setPassword("123456");

        if (userName.equals(userInfo.getUserName())){
            return userInfo;
        }else {
            return null;
        }
    }
}
import lombok.Data;

@Data
public class UserInfo {
    private String userName;
    private String password;
}

四、总结

以上就是 SpringBoot 中使用 Cookie 实现记住登录功能,在项目中还算是比较实用的功能

  • 6
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值