拦截器

210 阅读1分钟

image.png

@Component
public class LoginInterceptor implements HandlerInterceptor {
      @Autowired
      private StringRedisTemplate stringRedisTemplate;
      @Override
      public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
         //令牌验证
         String token = request.getHeader("Authorization");//密文验证,是否成功解析,报错

         try {
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            String s = operations.get(token);
            if (!s.equals(token)){
               throw new RuntimeException();
            }
            }
           

image.png

package com.itheima.config;

import com.itheima.interceptors.LoginInterceptor;
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 WebConfig implements WebMvcConfigurer {
@Autowired
LoginInterceptor loginInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
   //登入,注册接口不拦截
   registry.addInterceptor(loginInterceptor).excludePathPatterns("/user/login","/user/register");

}
}