SpringBoot中如何使用Cookie实现记住登录功能呢?
下文笔者讲述在SpringBoot中实现Cookie记住密码的效果分享,如下所示
Cookie简介
Cookie 存储在用户本地终端上的数据 Cookie是一个键值对的形式组成 服务器端响应Cookie到客户端 客户端会将Cookie存储起来,下次访问网站时,会将Cookie发送至服务器
Cookie相关说明
1、Cookie是HTTP协议的规范,用于服务器和客户端之间传输数据 2、Cookie的产生---先由服务器通过响应头把 Cookie 传输给客户端,客户端会将 Cookie 保存起来 3、当客户端再次请求同一服务器时,客户端会在请求头中添加该服务器保存Cookie,发送给服务器 4、Cookie是服务器保存在客户端的数据 5、Cookie数据采用键值对形式保存
Cookie使用
1、创建 Cookie
// Cookie 为键值对数据格式
Cookie cookie_username = new Cookie("cookie_username", username);
1
2
2、设置 Cookie 持久时间
// 即:过期时间,单位是:秒(s)
cookie_username.setMaxAge(30 * 24 * 60 * 60);
1
2
3、设置 Cookie 共享路径
// 表示当前项目下都携带这个cookie
cookie_username.setPath(request.getContextPath());
1
2
4、向客户端发送 Cookie
// 使用 HttpServletResponse 对象向客户端发送 Cookie
response.addCookie(cookie_username);
1
2
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);
SpringBoot实现Cookie记住登录
1、注册拦截器
/**
* 注册拦截器
*/
@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);
}
}
拦截了所有的请求路径,放开api、wechat等请求路径
2、登录拦截
/**
* 未登录拦截器
*/
@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、登录请求
控制层
/**
* 执行登录
*/
@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();
}
业务层
/**
* 执行登录
*/
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、注销登录
/**
* 退出登录
*/
@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";
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


