拦截器的使用

作者: gavin 分类: Java,Java 基础 发布时间: 2022-02-24 00:02

Step 1 创建拦截器(util/interceptor/TokenInterceptor.class)

package com.ren.draw.util.Interceptor;
import com.ren.draw.util.exception.RenException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * @author: Gavin
 * @created: 2022/2/23 23:44
 * @description:
 **/


 /**
  * 拦截器:Spring框架特有的,常用于登录校验,权限校验,请求日志打印 /login
  */
 @Component
 public class TokenInterceptor implements HandlerInterceptor {

     private static final Logger LOG = LoggerFactory.getLogger(TokenInterceptor.class);

     @Autowired
     HttpServletRequest httpServletRequest;

     @Resource
     private RedisTemplate redisTemplate;

     @Override
     public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
         String token = httpServletRequest.getHeader("token");
         LOG.info("token:"+token);
         if(ObjectUtils.isEmpty(token)) {
             throw new RenException("token不存在",401);
         }else if(ObjectUtils.isEmpty(redisTemplate.opsForValue().get(token))){
             throw new RenException("token无效",401);
         }
         // 打印请求信息
         LOG.info("------------- LogInterceptor 开始 -------------");
         LOG.info("请求地址: {} {}", request.getRequestURL().toString(), request.getMethod());
         LOG.info("远程地址: {}", request.getRemoteAddr());

         long startTime = System.currentTimeMillis();
         request.setAttribute("requestStartTime", startTime);
         return true;
     }

     @Override
     public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
         long startTime = (Long) request.getAttribute("requestStartTime");
         LOG.info("------------- LogInterceptor 结束 耗时:{} ms -------------", System.currentTimeMillis() - startTime);
     }
 }

Step 2 创建SpringMvcConfig配置文件

package com.ren.draw.util.config;

import com.ren.draw.util.Interceptor.TokenInterceptor;
import com.ren.draw.util.aop.Aspect;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;

/**
 * @author: Gavin
 * @created: 2022/2/23 23:23
 * @description:
 **/
@Configuration
public class SpringMvcConfig implements WebMvcConfigurer {

//    @Resource
//    Aspect aspect;

    @Resource
    TokenInterceptor tokenInterceptor;


    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(tokenInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns(
                        "/sysUser/login",
//                        "/swagger/**",
//                        "/swagger-resources/**",
                        "/doc.html",
                        "/v3/api-docs/**"
                );

//        registry.addInterceptor(actionInterceptor)
//                .addPathPatterns(
//                        "/*/save",
//                        "/*/delete/**",
//                        "/*/reset-password");
    }
}