date: 2025-03-24 21:50:09 title: Session Cookie身份认证 author: zaqai tags:
- Java
- SprintBoot
原理
session主要是存在内存中, 根据用户请求的cookie来识别用户身份
@RestController
public class SessionController {
@RequestMapping(path = "/login")
public String login(String uname, HttpSession httpSession) {
httpSession.setAttribute("name", uname);
return "欢迎登录:" + uname;
}
@RequestMapping("time")
public String showTime(HttpSession session) {
return session.getAttribute("name") + " ,当前时间为:" + LocalDateTime.now();
}
@RequestMapping("name")
public String showName(HttpServletRequest request) {
return "当前登录用户:" + request.getSession().getAttribute("name");
}
@RequestMapping(path = "logout")
public String logout(HttpSession httpSession) {
// 注销当前的session
httpSession.invalidate();
return "登出成功";
}
}
测试
登录获取JSESSIONID的cookie
访问
time
, 可以看到username, 注意也是同一个JSESSIONID
换用edge浏览器, JSESSIONID发生改变
换用curl API, 证明服务器只是通过JSESSIONID识别用户
回复