spring boot中interceptor拦截器未生效的解决

时间:2022-01-22 20:57:17

interceptor拦截器未生效

搭建项目时发现拦截器未生效

开始用的spring boot版本为1.5.6

代码如下:

?
1
2
3
4
5
6
7
8
9
10
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter{
 @Autowired
 private TimeInterceptor timeInterceptor;
 @Override
 public void addInterceptors(InterceptorRegistry registry) {
  registry.addInterceptor(this.timeInterceptor);
  super.addInterceptors(registry);
 }
}
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
@Component
public class RequestParamInfoIntorceptor extends HandlerInterceptorAdapter {
   private Logger logger = LoggerFactory.getLogger(RequestParamInfoIntorceptor.class);
     @Override
     public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
             throws Exception {
         try {
             if (handler instanceof HandlerMethod) {
                 HandlerMethod handlerMethod = (HandlerMethod) handler;
                 String beanName = handlerMethod.getBean().getClass().toString();//类
                 String methodName = handlerMethod.getMethod().getName();//方法名称
                 if(methodName.equals("error") || methodName.equals("success")) {
                     return super.preHandle(request, response, handler);
                 }
                 String uri = request.getRequestURI();//请求路径
                 String remoteAddr = getIpAddr(request);//ip
                 String method = request.getMethod(); //请求方式
                 Map<String,String[]> pramMap = request.getParameterMap();
                 StringBuffer sbf = new StringBuffer();
                 int count = 0;
                 String forCunt = "";
                 for(Map.Entry<String, String[]> entry:pramMap.entrySet()){ 
                     forCunt = "[" + count + "]" + " : " ;
                     sbf.append( "paramName" + forCunt + entry.getKey() + " - "+ "paramValue" +
                             forCunt + request.getParameter(entry.getKey()) + "\n");
                     count ++;
                 }
                 logger.info(" { beanName : " + beanName + " | " + "methodName : " + methodName + " | " + "uri : "
                         + uri + " | " + "remoteAddr : " + remoteAddr + " | " + "requestMethod : " +
                         method + "\n" + "param : " + sbf + "}");
             }
         } catch (Exception e) {
             //出错
             logger.error(e.toString());
         }
         return super.preHandle(request, response, handler);
     }
     //获取客户端IP
     private String getIpAddr(HttpServletRequest request) {
         String ip = request.getHeader("x-forwarded-for");
         if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
             ip = request.getHeader("Proxy-Client-IP");
         }
         if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
             ip = request.getHeader("WL-Proxy-Client-IP");
         }
         if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
             ip = request.getRemoteAddr();
         }
         return ip;
     }
}

开始以为是版本问题,后升级为2.1.1,WebConfig改为实现WebMvcConfigurer,代码如下

?
1
2
3
4
5
6
7
8
9
10
11
@Configuration
@Component
public class WebConfig implements WebMvcConfigurer{
 @Autowired
 private RequestParamInfoIntorceptor requestParamInfoIntorceptor;
 
 @Override
 public void addInterceptors(InterceptorRegistry registry) {
  registry.addInterceptor(this.requestParamInfoIntorceptor).addPathPatterns("/**");
 }
}

验证后还是不行,继续排查后发现,在添加版本控制时,有配置类继承了WebMvcConfigurationSupport,查询WebMvcConfigurationSupport源码发现其中有拦截器注册方法addInterceptors(InterceptorRegistry registry),所以在版本控制配置类中重写此方法添加拦截器,拦截器生效,问题解决。

解决方案

代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
@Configuration
public class ApiConfig extends WebMvcConfigurationSupport {
 @Autowired
 private RequestParamInfoIntorceptor requestParamInfoIntorceptor;
 
 @Override
 protected void addInterceptors(InterceptorRegistry registry) {
  registry.addInterceptor(this.requestParamInfoIntorceptor).addPathPatterns("/**");
  super.addInterceptors(registry);
 }
}

HandlerInterceptor实现登录失效拦截等

首先写一个实现HandlerInterceptor的类

代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
public class SessionInterceptor implements HandlerInterceptor {
    @Autowired
    RedisTemplate<String, String> redisTemplate;
    //private static String LOGIN_CODE = "/user/no_loginPage?Landingcode=" + UserResourcesHelper.LANDINGCODE_106;// 登录地址及code信息
    //private static String LOGIN_CODE = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxd11f95277f85e24b&redirect_uri=&response_type=code&scope=snsapi_userinfo&state=1234#wechat_redirect";
    protected List<String> patterns = new ArrayList<String>(Arrays.asList(".*?/.*/no_.*?", "/", "/error"));
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        // 一些不需要过滤的方法
        String url = request.getRequestURI();
        if (isInclude(url) == true)
            return true;
        // 权限校验
        Cookie cookie = getCookieByName(request, UserResourcesHelper.COOKIE_TOKEN_NAME);
        String user = null;
        if (cookie != null && !cookie.getValue().equals("")) {
            user = redisTemplate.opsForValue().get(RedisKeyConstant.USER_WEB_TOKEN + cookie.getValue());
        }
        if (cookie == null || user == null) {// 判断用户是否经过了授权
            // 判断是否是AJAX访问
            if (request.getHeader("x-requested-with") != null
                    && request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) {
                response.setHeader("sessionstatus", "timeout");
                response.setStatus(403);
                return false;
            } else {
                response.sendRedirect(request.getContextPath()+"/home/no_index_toLoginSkip");
                //response.sendRedirect(request.getContextPath() +UserResourcesHelper.LOGIN_URL); // 非AJAX访问,页面跳转
                //response.sendRedirect(request.getContextPath() +"https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxd11f95277f85e24b&redirect_uri="+URLEncoder.encode("http://m.hobay.cn/user/no_loginPage", "utf-8")+"&response_type=code&scope=snsapi_base&state=123#wechat_redirect"); // 非AJAX访问,页面跳转
                return false;
            }
        }
        return true;
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
    }
    private boolean isInclude(String url) {
        for (String pattern : patterns) {
            if (Pattern.matches(pattern, url)) {
                return true;
            }
        }
        return false;
    }
    /**
     * 根据名字获取cookie
     *
     * @param request
     * @param name
     *            cookie名字
     * @return
     */
    private static Cookie getCookieByName(HttpServletRequest request, String name) {
        Map<String, Cookie> cookieMap = ReadCookieMap(request);
        if (cookieMap.containsKey(name)) {
            Cookie cookie = (Cookie) cookieMap.get(name);
            return cookie;
        } else {
            return null;
        }
    }
    /**
     * 将cookie封装到Map里面
     *
     * @param request
     * @return
     */
    private static Map<String, Cookie> ReadCookieMap(HttpServletRequest request) {
        Map<String, Cookie> cookieMap = new HashMap<String, Cookie>();
        Cookie[] cookies = request.getCookies();
        if (null != cookies) {
            for (Cookie cookie : cookies) {
                cookieMap.put(cookie.getName(), cookie);
            }
        }
        return cookieMap;
    }

然后把这个拦截器注册到spring中

代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@EnableWebMvc
@Configuration
public class WebConfig  extends WebMvcConfigurerAdapter{
     @Bean
     SessionInterceptor sessioninterceptor() {
         return new SessionInterceptor();
    }
    /**
     * 配置拦截器
     * @author yuqingquan
     * @param registry
     */
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(sessioninterceptor());
    }

以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/sorrow_yc/article/details/88736732