SpringMVC-DispatcherServlet流程解析
前言
在Spring MVC中处理HTTP请求时如果抛出异常会使用DispatcherServlet#processHandlerException()处理,这个方法内部使用Spring MVC默认的注册的HandlerExceptionResolver进行处理。
processHandlerException
1 |
|
Spring MVC默认注册了三个HandlerExceptionResolver:
- ExceptionHandlerExceptionResolver
- ResponseStatusExceptionResolver
- DefaultHandlerExceptionResolver
HandlerExceptionResolver
是异常处理器的接口
1 | public interface HandlerExceptionResolver { |
继承关系
AbstractHandlerExceptionResolver
HandlerExceptionResolver实现的抽象基类。支持设置映射处理程序setMappedHandlers()和setMappedHandlerClasses(),解析器应该应用于并实现Ordered接口。
1 | public abstract class AbstractHandlerExceptionResolver implements HandlerExceptionResolver, Ordered { |
AbstractHandlerMethodExceptionResolver
HandlerExceptionResolver实现的抽象基类,支持处理类型为HandlerMethod的处理程序的异常。
1 | public abstract class AbstractHandlerMethodExceptionResolver extends AbstractHandlerExceptionResolver { |
ExceptionHandlerExceptionResolver
是一个AbstractHandlerMethodExceptionResolver,它通过@ExceptionHandler方法解决异常。可以通过setCustomArgumentResolvers()和setCustomReturnValueHandlers()添加对自定义参数和返回值类型的支持。
或者,重新配置所有参数和返回值类型使用setArgumentResolvers()和setReturnValueHandlers(List)。
1 | /** |
ResponseStatusExceptionResolver
一个HandlerExceptionResolver,它使用@ResponseStatus注释将异常映射到HTTP状态代码。
默认情况下,在{@link org.springframework.web.servlet.DispatcherServlet DispatcherServlet}以及MVC Java配置和MVC命名空间中启用此异常解析程序。
从4.2开始,这个解析器也会以@ResponseStatus递归查找原因异常,从4.2.2开始,此解析器支持自定义组合注释中@ResponseStatus的属性覆盖。
从5.0开始,这个解析器也支持ResponseStatusException。
1 | public class ResponseStatusExceptionResolver extends AbstractHandlerExceptionResolver implements MessageSourceAware { |
DefaultHandlerExceptionResolver
HandlerExceptionResolver接口的默认实现,解析标准的Spring MVC异常并将它们转换为相应的HTTP状态代码。
默认情况下,在常见的Spring DispatcherServlet中启用此异常解析程序
支持的异常
异常 | HTTP状态码 |
---|---|
HttpRequestMethodNotSupportedException | 405 (SC_METHOD_NOT_ALLOWED) |
HttpMediaTypeNotSupportedException | 415 (SC_UNSUPPORTED_MEDIA_TYPE) |
HttpMediaTypeNotAcceptableException | 406 (SC_NOT_ACCEPTABLE) |
MissingPathVariableException | 500 (SC_INTERNAL_SERVER_ERROR) |
MissingServletRequestParameterException | 400 (SC_BAD_REQUEST) |
ServletRequestBindingException | 400 (SC_BAD_REQUEST) |
ConversionNotSupportedException | 500 (SC_INTERNAL_SERVER_ERROR) |
TypeMismatchException | 400 (SC_BAD_REQUEST) |
HttpMessageNotReadableException | 400 (SC_BAD_REQUEST) |
HttpMessageNotWritableException | 500 (SC_INTERNAL_SERVER_ERROR) |
MethodArgumentNotValidException | 400 (SC_BAD_REQUEST) |
MissingServletRequestPartException | 400 (SC_BAD_REQUEST) |
BindException | 400 (SC_BAD_REQUEST) |
NoHandlerFoundException | 404 (SC_NOT_FOUND) |
AsyncRequestTimeoutException | 503 (SC_SERVICE_UNAVAILABLE) |