三种异常页面

  1. 自定义的错误页面
    异常页面 - 图1
  2. SpringBoot的错误页面
    异常页面 - 图2
  3. Tomcat的错误页面
    异常页面 - 图3

异常页面 - 图6
tomcat收到response为404,dispatch到/error页面。
tomcat收到response为404,dispatch到/error页面。
tomcat收到response为404,dispatch到/error页面。
dispatch前端无感知。

/error 找到controller【BasicErrorController】

/error RequestMappingHandlerMapping根据找到BasicErrorController
image.png

BasicErrorController处理

image.png

Controller中调用ErrorViewResolver(DefaultErrorViewResolver)处理

image.png

ErrorViewResolver中处理【判断4xx.html】

image.png
依次判断

  • error/4xx.html
  • resources/error/4xx.html
  • static/error/4xx.html
  • public/error/4xx.html

都没有,最后返回ModelAndView = null

没找到ModelAndView,构造一个viewName为error的ModelAndView

image.png

路过returnValueHandlers

processDispatchResult

render

ResolveViewName:利用ViewResolver根据名字解析出View

image.png

StaticView就是最终显示的View

image.png
异常页面 - 图14

view.render:显示页面

自定义错误页面

方式一:添加ErrorPage

老:

  1. @Configuration
  2. public class ErrorPageConfig {
  3. @Bean
  4. public EmbeddedServletContainerCustomizer containerCustomizer() {
  5. return new EmbeddedServletContainerCustomizer() {
  6. public void customize(ConfigurableEmbeddedServletContainer container) {
  7. ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/static/html/500.html");
  8. ErrorPage error500Page = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/static/html/500.html");
  9. container.addErrorPages(error404Page, error500Page);
  10. }
  11. };
  12. }
  13. }

新:

  1. @Configuration
  2. public class ContainerConfig implements ErrorPageRegistrar {
  3. @Override
  4. public void registerErrorPages(ErrorPageRegistry registry) {
  5. ErrorPage[] errorPages = new ErrorPage[2];
  6. errorPages[0] = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error/500");
  7. errorPages[1] = new ErrorPage(HttpStatus.NOT_FOUND, "/error/404");
  8. registry.addErrorPages(errorPages);
  9. }
  10. }

方式二:重写名字为Error的View

定义view

  1. public class GunsErrorView implements View {
  2. @Override
  3. public String getContentType() {
  4. return "text/html";
  5. }
  6. @Override
  7. public void render(Map<String, ?> map, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
  8. httpServletRequest.getRequestDispatcher("/global/error").forward(httpServletRequest, httpServletResponse);
  9. }
  10. }

view解析将跳转到/global/error(自定义Controller)
配置error view

  1. //bean名称必须为error,
  2. @Bean("error")
  3. public GunsErrorView error() {
  4. return new GunsErrorView();
  5. }

方式三:自定义ErrorViewResolver

ErrorViewResolver在BasicErrorController中被使用。返回ModelAndView。