简体   繁体   English

如何让拦截器在springboot中工作

[英]How to let Interceptor work in springboot

I migrate the code to springboot and our API works well.我将代码迁移到 springboot,我们的 API 运行良好。 Only interceptor can't be triggerred.只有拦截器不能被触发。 I googled related solutions and modify the code to right format which still failed to trigger the interceptor.我搜索了相关的解决方案并将代码修改为正确的格式,但仍然无法触发拦截器。

In our project, we also have the filter which extends OncePerRequestFilter and works.在我们的项目中,我们还有一个扩展了 OncePerRequestFilter 并且可以工作的过滤器。 It makes me confused.这让我很困惑。 They should be no big difference.他们应该没有太大区别。

Btw, AOP is used in the project.顺便说一句,项目中使用了AOP。 It's my code.这是我的代码。

JerseyConfig.class JerseyConfig.class

@Configuration
public class JerseyConfig extends ResourceConfig {
    public JerseyConfig(){
        packages("com.xxx");
    }
}

VaultAuthorizationInterceptor.class VaultAuthorizationInterceptor.class

@Component
public class VaultAuthorizationInterceptor implements HandlerInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(VaultAuthorizationInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        logger.info("test");
        return true;
    }
}

VaultAuthConfig.class VaultAuthConfig.class

@Configuration
public class VaultAuthConfig implements WebMvcConfigurer {

    @Bean
    public VaultAuthorizationInterceptor getVaultInterceptor() {
        return new VaultAuthorizationInterceptor();
    }
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(getVaultInterceptor()).addPathPatterns("/**");
    }
}

When you are using the spring-boot-starter-jersey, you use jersey as your web stack.当您使用 spring-boot-starter-jersey 时,您使用 jersey 作为您的 web 堆栈。 That means any requests will processed by jersey.这意味着任何请求都将由 jersey 处理。 So you have to register a jersey filter or interceptor.所以你必须注册一个 jersey 过滤器或拦截器。 Take a look at the jersey documantation .看看jersey 文档 There is described how to use filters and interceptors.描述了如何使用过滤器和拦截器。 I think you want to use a filter because interceptors in the jersey stack used to manipulate the input or output stream.我认为您想使用过滤器,因为 jersey 堆栈中的拦截器用于操纵输入或 output stream。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM