Interception

所有 HandlerMapping 实现都支持处理程序拦截,这在想要在多个请求中应用功能时非常有用。HandlerInterceptor 可以实现以下功能:

All HandlerMapping implementations support handler interception which is useful when you want to apply functionality across requests. A HandlerInterceptor can implement the following:

  • preHandle(..) — callback before the actual handler is run that returns a boolean. If the method returns true, execution continues; if it returns false, the rest of the execution chain is bypassed and the handler is not called.

  • postHandle(..) — callback after the handler is run.

  • afterCompletion(..) — callback after the complete request has finished.

对于 @ResponseBodyResponseEntity 控制器方法,响应是在调用 postHandle 之前在 HandlerAdapter 中写入并提交的。这意味着已经太晚而无法更改响应,例如添加附加标头。您可以实现 ResponseBodyAdvice 并将其声明为 Controller Advice bean,也可以在 RequestMappingHandlerAdapter 中直接对其进行配置。

For @ResponseBody and ResponseEntity controller methods, the response is written and committed within the HandlerAdapter, before postHandle is called. That means it is too late to change the response, such as to add an extra header. You can implement ResponseBodyAdvice and declare it as an Controller Advice bean or configure it directly on RequestMappingHandlerAdapter.

有关配置拦截器的示例,请参阅 MVC 配置部分中的 Interceptors。您还可以通过对各个 HandlerMapping 实现使用 setter 直接注册它们。

See Interceptors in the section on MVC configuration for examples of how to configure interceptors. You can also register them directly by using setters on individual HandlerMapping implementations.

由于可能与带注释的控制器路径匹配不匹配,因此拦截器不适合作为安全层。通常,我们建议使用 Spring Security,或将类似的方法与 Servlet 过滤器链集成并尽早应用。

Interceptors are not ideally suited as a security layer due to the potential for a mismatch with annotated controller path matching. Generally, we recommend using Spring Security, or alternatively a similar approach integrated with the Servlet filter chain, and applied as early as possible.