登录测试的controller:loginTest.java
package com.example.demo.controller; import com.example.demo.po.ResponseBean; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; import java.util.UUID; import java.util.concurrent.TimeUnit; /** * @Date 2023/7/2 - 12:33 */ @RestController @RequestMapping("loginTest") public class loginTest { @Resource private RedisTemplate redisTemplate; @GetMapping("/login") public ResponseBean<String> login(@RequestBody String user){ System.out.println("user:"+user); ResponseBean responseBean=null; // 用uuid生成一个字符串作为token String token="token-"+UUID.randomUUID(); // 写到redis中,并且设置过期时间为30min,这里的user模拟登录成功后的用户唯一标识 redisTemplate.opsForValue().set(token,user,30, TimeUnit.MINUTES); // 用响应类封装这个token responseBean=new ResponseBean(token); return responseBean; } }
拦截器:loginInterceptor.java
package com.example.demo.interceptor; import com.example.demo.po.ResponseBean; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.web.servlet.HandlerInterceptor; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.concurrent.TimeUnit; public class loginInterceptor implements HandlerInterceptor { @Resource private RedisTemplate redisTemplate; // 在请求被处理之前执行的逻辑,可以通过返回值决定是否继续处理请求。 @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("preHandle"); ResponseBean responseBean = null; // 从请求头获取token String token = request.getHeader("token"); if (token == null || token.equals("")) { responseBean = new ResponseBean(600, "用户未登录"); String json = new ObjectMapper().writeValueAsString(responseBean); //将响应对象转换成json response.setContentType("application/json;charset=UTF-8"); //设置响应数据类型为utf-8 response.getWriter().println(json); //将json响应给前端 return false; } if (redisTemplate.opsForValue().get(token) == null||"".equals(redisTemplate.opsForValue().get(token))) { responseBean = new ResponseBean(601, "token已过期"); String json = new ObjectMapper().writeValueAsString(responseBean); //将响应对象转换成json response.setContentType("application/json;charset=UTF-8"); //设置响应数据类型为utf-8 response.getWriter().println(json); //将json响应给前端 return false; } if (redisTemplate.opsForValue().get(token) != null||!"".equals(redisTemplate.opsForValue().get(token))) { // 在请求后重置redis过期时间 redisTemplate.expire(token, 30, TimeUnit.MINUTES); return true; } return false; } }
用来验证拦截器中token的接口,随便响应点东西
拦截器中把login的接口排除拦截
测试:
先请求登录接口,返回token
将token写入请求头,向其他接口发送请求,正常响应