1 回答
TA贡献1789条经验 获得超8个赞
如果你有一个 springboot 应用程序来拦截对控制器的请求,你必须采取不同的方法。
拦截器与 Java EE 托管类结合使用,以允许开发人员在关联的目标类上调用拦截器方法,并结合方法调用或生命周期事件。拦截器的常见用途是日志记录、审计和分析。参考文档
您正在尝试将 Java EE 注释与 spring 一起使用,这是行不通的。在 spring-boot 中,您必须注册拦截器,例如:
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LocaleChangeInterceptor());
registry.addInterceptor(new ThemeChangeInterceptor()).addPathPatterns("/**").excludePathPatterns("/admin/**");
registry.addInterceptor(new SecurityInterceptor()).addPathPatterns("/secure/*");
}
}
拦截器本身必须是一个扩展HandlerInterceptorAdapter 并实现如下方法的类。来自 Spring文档:
所有 HandlerMapping 实现都支持处理程序拦截器,当您想要将特定功能应用于某些请求时,这些拦截器很有用——例如,检查主体。拦截器必须使用 org.springframework.web.servlet 包中的三个方法实现 HandlerInterceptor,这三个方法应该提供足够的灵活性来进行各种预处理和后处理:
preHandle(..): Before the actual handler is executed
postHandle(..): After the handler is executed
afterCompletion(..): After the complete request has finished
@Component
public class RequestInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object object) throws Exception {
System.out.println("we are Intercepting the Request");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response,
Object object, ModelAndView model)
throws Exception {
System.out.println("request processing "
+ "completed by @RestController");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
Object object, Exception arg3)
throws Exception {
System.out.println("afterCompletion Request Completed");
}
}
添加回答
举报