-
会话技术
-
JWT令牌
-
过滤器Filter
-
拦截器 interceptor
cookise
package com.it.controller;import com.it.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;@Slf4j
@RestController
public class SessionController {//设置cookie@GetMapping("/c1")public Result cookie1(HttpServletResponse response){response.addCookie(new Cookie("login_username","it")); //设置cookie /响应cookiereturn Result.success();}//获取cookie@GetMapping("/c2")public Result cookie2(HttpServletRequest request){Cookie[] cookies = request.getCookies();//获取所有的cookiefor (Cookie cookie : cookies) {if (cookie.equals("login_username")){ //输出name为login_username 的cookieSystem.out.println("login_username:"+cookie.getValue());}}return Result.success();}}
session
//往httpSession中存储值@GetMapping("/s1")public Result sessio1(HttpSession session){log.info("HttpSession-s1 :{}",session.hashCode());session.setAttribute("loginUser","mamat");return Result.success();}// 往HttpSession 中的取值@GetMapping("/s2")public Result session2(HttpServletRequest request){HttpSession session =request.getSession();log.info("HttpSession-s2:{}",session);Object loginUser= session.getAttribute("loginUser") ; //从session获取数据log.info("loginUser:{}",loginUser);return Result.success(loginUser);}
jwt令牌 引入依赖
<dependency><groupId>io.jsonwebtoken</groupId><artifactId>jjwt</artifactId><version>0.9.1</version></dependency>
package com.it.utils;import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;import java.util.Date;
import java.util.Map;public class JwtUtils {public static String signKey ="itWord"; //密钥public static Long expire = 43200000L; //密钥 一分钟等于1000 毫秒 (43200000L 12小时)//生成JWT令牌ypublic static String generateJwt(Map<String,Object> claims){String jwt= Jwts.builder().addClaims(claims).signWith(SignatureAlgorithm.HS256,signKey).setExpiration(new Date(System.currentTimeMillis()+expire)).compact();return jwt;}//解析JWT令牌public static Claims parseJWT(String jwt){Claims claims =Jwts.parser().setSigningKey(signKey).parseClaimsJwt(jwt).getBody();return claims;}
}
JWT令牌生成调用
@PostMapping("/login")public Result login(@RequestBody Emp emp){log.info("员工登录,:{}",emp);Emp emp1 =empservice.login(emp);// 登录成功 生成令牌 下发令牌if (emp1!=null){Map<String, Object> claims =new HashMap<>();claims.put("id",emp1.getId());claims.put("name",emp1.getName());claims.put("username",emp1.getUsername()); // jwt令牌包含当前登录的员工信息String jwt = JwtUtils.generateJwt(claims);return Result.success(jwt);}return Result.error("用户名或者密码错误");}
过滤器拦截调用
package com.it.filter;import com.alibaba.fastjson.JSONObject;import com.it.pojo.Result;
import com.it.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;@Slf4j
@WebFilter(urlPatterns = "/*")
public class LoginCheckFilter implements Filter {@Overridepublic void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {//强转HttpServletRequest rep=(HttpServletRequest) servletRequest;HttpServletResponse resp=(HttpServletResponse) servletResponse;// 1:获取请求urlString url = rep.getRequestURI().toString();log.info("请求路径:{}",url);// 2:判断请求URl中是否包含login, 如果包含说明登录操作 可以放行if (url.contains("login")){log.info("登录操作 ,放行");filterChain.doFilter(servletRequest,servletResponse);return;}// 3: 获取请求头中的令牌(token)String jwt = rep.getHeader("token");log.info("Jwt,令牌数据:{}",jwt);// 4: 判断令牌是否存在 ,如果不存在,返回错误结果 (未登录)if (!StringUtils.hasLength(jwt)){log.info("请求头token为空 返回未登录信息");Result error = Result.error("NOT_LOGIN");// 手动转换对象-- json ----->阿里巴巴fastJsonString notLogin = JSONObject.toJSONString(error);resp.getWriter().write(notLogin);return;}// 5:解析token, 如果解析失败 。返回错误结果(未登录)try {JwtUtils.parseJWT(jwt);} catch (Exception e) { //jwt 解析失败e.printStackTrace();log.info("解析令牌解析失败 返回未登录错误信息");Result error = Result.error("NOT_LOGIN");// 手动转换对象-- json ----->阿里巴巴fastJsonString notLogin = JSONObject.toJSONString(error);resp.getWriter().write(notLogin);return;}// 6:放行log.info("令牌合法 放行");filterChain.doFilter(servletRequest,servletResponse);}
}