spring boot中interceptor拦截器未生效

搭建项目时发现拦截器未生效,开始用的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);
	}
	
}

 

  • 6
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Spring Boot provides a way to intercept method calls using Method Interceptor. Method Interceptor allows you to intercept a method call before and after the method is called. This is useful when you want to add some additional behavior to a method, such as logging or security checks. To create a method interceptor in Spring Boot, you need to create a class that implements the `MethodInterceptor` interface from the `org.aopalliance.intercept` package. This interface has two methods: 1. `Object invoke(MethodInvocation invocation) throws Throwable`: This method is called before and after the method is executed. The `MethodInvocation` object contains information about the method call and allows you to manipulate the method parameters and return value. 2. `MethodInterceptor getInterceptor()`: This method returns the actual interceptor that will be used to intercept the method call. Here's an example of how to create a method interceptor in Spring Boot: ```java import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; public class LoggingInterceptor implements MethodInterceptor { @Override public Object invoke(MethodInvocation invocation) throws Throwable { System.out.println("Before method call: " + invocation.getMethod().getName()); Object result = invocation.proceed(); System.out.println("After method call: " + invocation.getMethod().getName()); return result; } } ``` In this example, the `LoggingInterceptor` class implements the `MethodInterceptor` interface and overrides the `invoke` method to log the method name before and after the actual method call. To use this interceptor, you need to configure it in your Spring Boot application context: ```java import org.springframework.aop.framework.ProxyFactoryBean; @Configuration public class AppConfig { @Bean public LoggingInterceptor loggingInterceptor() { return new LoggingInterceptor(); } @Bean public MyService myService() { ProxyFactoryBean proxyFactoryBean = new ProxyFactoryBean(); proxyFactoryBean.setTarget(new MyServiceImpl()); proxyFactoryBean.setInterceptorNames("loggingInterceptor"); return (MyService) proxyFactoryBean.getObject(); } } ``` In this example, the `loggingInterceptor` bean is created and configured to intercept method calls. The `MyService` bean is also created and configured to use the `loggingInterceptor` for method interception. When a method is called on the `MyService` bean, the `LoggingInterceptor` will intercept the method call and log the method name before and after the actual method call.
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值