cookie 在请求头中叫做cookie,在响应头中叫set-cookie
@GetMapping("/c1")
public Result cookie1(HttpServletResponse resp){
resp.addCookie(new Cookie("login_name","itheima"));
return Result.success();
}
@GetMapping("/c2")
public Result cookie2(HttpServletRequest request){
Cookie [] cookies = request.getCookies();
for(Cookie cookie : cookies){
if(cookie.getName().equals("login_username")){
System.out.println("login_username" + cookie.getValue());
}
}
return Result.success();
}
当前所在位置和请求位置,然后从3维度来判断是否是跨哉请求,只要有一个不同就属于
session基于cookie实现
java
@GetMapping("/s1")
public Result session1(HttpSession session){
session.setAttribute("loginUser", "tom");
return Result.success();
}
@GetMapping("/s2")
public Result session2(HttpServletRequest request){
HttpSession session = request.getSession();
Object loginUser = session.getAttribute("loginUser");
return Result.success(loginUser);
}
拦截器
Filter
java
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) servletRequest;
HttpServletResponse resp = (HttpServletResponse)servletResponse;
//获取请求的url
String url = req.getRequestURL().toString();
//判断是否包含登录
if(url.contains("login")){
filterChain.doFilter(req, resp);
return;
}
//获取请求头中的令牌
String jwt = req.getHeader("token");
if(!StringUtils.hasLength(jwt)){ //如果为空
Result errorRet = Result.error("NOT_LOGIN");
//阿里巴巴fastJson
String notLogin = JSONObject.toJSONString(errorRet);
//将json字符串返回给浏览器
resp.getWriter().write(notLogin);
}
//解析token,如果解析失败,返回错误结果
try {
JwtUtils.parseJwt(jwt);
} catch(Exception e){
Result errorRet = Result.error("NOT_LOGIN");
//阿里巴巴fastJson
String notLogin = JSONObject.toJSONString(errorRet);
//将json字符串返回给浏览器
resp.getWriter().write(notLogin);
return;
}
//放行
filterChain.doFilter(req, resp);
}