java session和cookie的存值和取值
本文cookie和session的存值和取值以及拦截器token验证
pom添加依赖
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.5.6</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.stu</groupId> <artifactId>boot-init</artifactId> <version>0.0.1-SNAPSHOT</version> <name>boot-init</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.2.0</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>com.auth0</groupId> <artifactId>java-jwt</artifactId> <version>3.10.3</version> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version>0.9.1</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
LoginController
package com.stu.controller; import io.jsonwebtoken.JwtBuilder; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; 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.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.util.Date; import java.util.HashMap; import javax.servlet.http.Cookie; @RestController @RequestMapping("/login") public class LogonController { @RequestMapping("/login") public String login(HttpServletRequest request, HttpServletResponse response, HttpSession session){ Cookie c = new Cookie("logincodecookie",""); c.setMaxAge(60*60*24*14); //2周时间Cookie过期 单位秒 c.setPath("/"); //表示任何请求路径都可以访问Cookie response.addCookie(c); session.setAttribute("loginsession","sessoin"); //如果登录验证成功,则需要生成令牌token(token就是按照特定规则生成的字符串) //使用jwt规则生成token字符串 JwtBuilder builder = Jwts.builder(); HashMap<String,Object> map = new HashMap<>(); map.put("key1","value1"); map.put("key2","value2"); String token = builder.setSubject("tokenName") //主题,就是token中携带的数据 .setIssuedAt(new Date()) //设置token的生成时间 .setId("userId123456" + "") //设置用户id为token id .setClaims(map) //map中可以存放用户的角色权限信息 .setExpiration(new Date(System.currentTimeMillis() + 24*60*60*1000)) //设置token过期时间 .signWith(SignatureAlgorithm.HS256, "QIANfeng6666") //设置加密方式和加密密码 .compact(); return token; } @RequestMapping("/loginAfter") public void loginAfter(HttpServletRequest request, HttpServletResponse response, HttpSession session){ System.out.println("获取到Cookie中的键值对 loginAfter"); } }
InterceptorConfig拦截器注册
package com.stu.controller.config; import com.stu.controller.interceptor.CheckTokenInterceptor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class InterceptorConfig implements WebMvcConfigurer { @Autowired private CheckTokenInterceptor checkTokenInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(checkTokenInterceptor) .addPathPatterns("/**").excludePathPatterns("/login/login"); } }
CheckTokenInterceptor拦截器
package com.stu.controller.interceptor; import com.fasterxml.jackson.databind.ObjectMapper; import com.stu.controller.vo.ResultVO; import io.jsonwebtoken.*; import org.springframework.stereotype.Component; 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; import java.io.IOException; import java.io.PrintWriter; @Component public class CheckTokenInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String method = request.getMethod(); if("OPTIONS".equalsIgnoreCase(method)){ return true; } HttpSession session = request.getSession(); Object user = session.getAttribute("loginsession"); Cookie[] cookies = request.getCookies(); if(cookies != null){ for (Cookie cookie : cookies) { if("logincodecookie".equals(cookie.getName())) { System.out.println("获取到Cookie中的键值对" + cookie.getName() + "===== " + cookie.getValue()); } } } String token = request.getHeader("token"); if(token == null){ ResultVO resultVO = new ResultVO(20001, "请先登录!", null); doResponse(response,resultVO); }else{ try { JwtParser parser = Jwts.parser(); parser.setSigningKey("QIANfeng6666"); //解析token的SigningKey必须和生成token时设置密码一致 //如果token正确(密码正确,有效期内)则正常执行,否则抛出异常 Jws<Claims> claimsJws = parser.parseClaimsJws(token); return true; }catch (ExpiredJwtException e){ ResultVO resultVO = new ResultVO(20002, "登录过期,请重新登录!", null); doResponse(response,resultVO); }catch (UnsupportedJwtException e){ ResultVO resultVO = new ResultVO(20001, "Token不合法,请自重!", null); doResponse(response,resultVO); }catch (Exception e){ ResultVO resultVO = new ResultVO(20001, "请先登录!", null); doResponse(response,resultVO); } } return false; } private void doResponse(HttpServletResponse response,ResultVO resultVO) throws IOException { response.setContentType("application/json"); response.setCharacterEncoding("utf-8"); PrintWriter out = response.getWriter(); String s = new ObjectMapper().writeValueAsString(resultVO); out.print(s); out.flush(); out.close(); } }