欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

spring boot中interceptor拦截器未生效

程序员文章站 2022-05-23 15:53:06
...

搭建项目时发现拦截器未生效,开始用的spring boot版本为1.5.6,代码如下

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter{

	@Autowired
	private TimeInterceptor timeInterceptor;
	
	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(this.timeInterceptor);
		super.addInterceptors(registry);
	}
}
@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,代码如下

@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),所以在版本控制配置类中重写此方法添加拦截器,拦截器生效,问题解决。代码如下:

@Configuration
public class ApiConfig extends WebMvcConfigurationSupport {
	
	@Autowired
	private RequestParamInfoIntorceptor requestParamInfoIntorceptor;
	
	@Override
	protected void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(this.requestParamInfoIntorceptor).addPathPatterns("/**");
		super.addInterceptors(registry);
	}
	
}