首页 文章

spring boot添加http请求拦截器

提问于
浏览
77

在Spring启动应用程序中添加HttpRequest拦截器的正确方法是什么?我想要做的是为每个http请求记录请求和响应 .

Spring启动文档根本不涉及此主题 . (http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/

我发现了一些关于如何对旧版本的spring执行相同操作的Web示例,但这些示例与applicationcontext.xml一起使用 . 请帮忙 .

5 回答

  • 122

    因为你希望尽可能依赖Spring的自动配置 . 要添加其他自定义配置(如拦截器),只需提供 WebMvcConfigurerAdapter 的配置或bean .

    这是一个配置类的示例:

    @Configuration
    public class WebMvcConfig extends WebMvcConfigurerAdapter {
    
      @Autowired 
      HandlerInterceptor yourInjectedInterceptor;
    
      @Override
      public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(...)
        ...
        registry.addInterceptor(getYourInterceptor()); 
        registry.addInterceptor(yourInjectedInterceptor);
        // next two should be avoid -- tightly coupled and not very testable
        registry.addInterceptor(new YourInterceptor());
        registry.addInterceptor(new HandlerInterceptor() {
            ...
        });
      }
    }
    

    NOTE 如果要保留Spring Boots auto configuration for mvc,请不要使用@EnableWebMvc注释 .

  • 22

    WebMvcConfigurerAdapter 将在Spring 5中弃用 . 来自Javadoc

    @deprecated从5.0开始{@link WebMvcConfigurer}具有默认方法(由Java 8基线实现)并且可以直接实现而无需此适配器

    如上所述,您应该做的是实现 WebMvcConfigurer 并覆盖 addInterceptors 方法 .

    @Configuration
    public class WebMvcConfig implements WebMvcConfigurer {
    
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(new MyCustomInterceptor());
        }
    }
    
  • 6

    要将拦截器添加到Spring引导应用程序,请执行以下操作

    • 创建一个拦截器类
    public class MyCustomInterceptor implements HandlerInterceptor{
    
        //unimplemented methods comes here. Define the following method so that it     
        //will handle the request before it is passed to the controller.
    
        @Override
        public boolean preHandle(HttpServletRequest request,HttpServletResponse  response){
        //your custom logic here.
            return true;
        }
    }
    
    • 定义配置类
    @Configuration
    public class MyConfig extends WebMvcConfigurerAdapter{
        @Override
        public void addInterceptors(InterceptorRegistry registry){
            registry.addInterceptor(new MyCustomInterceptor()).addPathPatterns("/**");
        }
    }
    
    • 多数民众赞成吧 . 现在,您的所有请求都将通过MyCustomInterceptor的preHandle()方法中定义的逻辑 .
  • 51

    我有同样的问题WebMvcConfigurerAdapter被弃用 . 当我搜索示例时,我几乎找不到任何实现的代码 . 这是一段工作代码 .

    创建一个扩展HandlerInterceptorAdapter的类

    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.stereotype.Component;
    import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
    
    import me.rajnarayanan.datatest.DataTestApplication;
    @Component
    public class EmployeeInterceptor extends HandlerInterceptorAdapter {
        private static final Logger logger = LoggerFactory.getLogger(DataTestApplication.class);
        @Override
        public boolean preHandle(HttpServletRequest request, 
                HttpServletResponse response, Object handler) throws Exception {
    
                String x = request.getMethod();
                logger.info(x + "intercepted");
            return true;
        }
    
    }
    

    然后实现WebMvcConfigurer接口

    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;
    
    import me.rajnarayanan.datatest.interceptor.EmployeeInterceptor;
    @Configuration
    public class WebMvcConfig implements WebMvcConfigurer {
        @Autowired
        EmployeeInterceptor employeeInterceptor ;
    
        @Override
        public void addInterceptors(InterceptorRegistry registry){
            registry.addInterceptor(employeeInterceptor).addPathPatterns("/employee");
        }
    }
    
  • 6

    您也可以考虑使用开源SpringSandwich库,它允许您直接在控制器中注释要应用哪些拦截器,就像您为url路由注释一样 .

    这样,SpringSandwich的方法和类注释很容易在重构中存活,并且清楚地说明了应用于何处 . (披露:我是作者) .

    http://springsandwich.com/

相关问题