@Component
public class TestInterceptor implements HandlerInterceptor {
@Override
public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception {
System.out.println("afterCompletion");
}
@Override
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3) throws Exception {
System.out.println("postHandle");
}
@Override
public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
System.out.println("preHandle");
return true;
}
}
和
@SpringBootConfiguration
public class AnnotationSecurityConfiguration implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new TestInterceptor()).addPathPatterns("/api/**");
}
}
最后,使用@repositoryrestcontroller将实体表示为rest,如下所示:
@RepositoryRestResource(excerptProjection = UserSummaryProjection.class)
public interface UserRepository extends JpaRepository<User, Long>, JpaSpecificationExecutor<User> {
}
然后打电话来
curl -X GET https://localhost:8080/api/v1/users
但是拦截器没有被调用。
因为rest资源是用@repositoryrestcontroller管理的spring数据rest,所以不会调用拦截器。但是如果我用@restcontroller编写rest资源,它就会工作。
如何使拦截器与@repositoryrestcontroller一起工作?
2条答案
按热度按时间vuktfyat1#
我把它修好了
/
上下文路径和一个简单的User
类,spring boot v2.4.2)和以下config/spring boot应用程序:我用了一个简化的:
lnlaulya2#
你必须加上
TestInterceptor
就像一颗豆子,用它来涂油@Autowired
只需添加以下更改即可将拦截器注册到拦截器注册表中:拦截器:
作为示例,我将“/api/”更改为“/”,下面是一个日志示例: