成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

Springboot默認的錯誤頁是如何工作及工作原理你肯定不知道?

開發 前端
到此你就知道了一個錯誤的頁是如何在Springboot中被注冊的。到目前為止我們看到的注冊到tomcat容器中的錯誤頁都是個地址,比如:默認是/error。那這個默認的/error又是怎么提供的接口呢?

環境:Springboot2.4.12

環境配置

接下來的演示都是基于如下接口進行。

@RestController
@RequestMapping("/exceptions")
public class ExceptionsController {
    
  @GetMapping("/index")
  public Object index(int a) {
    if (a == 0) {
      throw new BusinessException() ;
    }
    return "exception" ;
  }
    
}

默認錯誤輸出

默認情況下,當請求一個接口發生異常時會有如下兩種情況的錯誤信息提示

  • 基于HTML

圖片圖片

  • 基于JSON

圖片圖片

上面兩個示例通過請求的Accept請求頭設置希望接受的數據類型,得到不同的響應數據類型。

標準web錯誤頁配置

在標準的java web項目中我們一般是在web.xml文件中進行錯誤頁的配置,如下:

<error-page>
  <location>/error</location>
</error-page>

如上配置后,如發生了異常以后容器會自動地跳轉到錯誤頁面。

Spring實現原理

在Springboot中沒有web.xml,并且Servlet API也沒有提供相應的API進行錯誤頁的配置。那么在Springboot中又是如何實現錯誤頁的配置呢?

Springboot內置了應用服務,如Tomcat,Undertow,Jetty,默認是Tomcat。那接下來看下基于默認的Tomcat容器錯誤頁是如何進行配置的。

  • Servlet Web服務自動配置
@EnableConfigurationProperties(ServerProperties.class)
@Import({ServletWebServerFactoryAutoConfiguration.BeanPostProcessorsRegistrar.class, 
         ServletWebServerFactoryConfiguration.EmbeddedTomcat.class,...})
public class ServletWebServerFactoryAutoConfiguration {
  @Configuration(proxyBeanMethods = false)
  @ConditionalOnClass({ Servlet.class, Tomcat.class, UpgradeProtocol.class })
  @ConditionalOnMissingBean(value = ServletWebServerFactory.class, search = SearchStrategy.CURRENT)
  static class EmbeddedTomcat {


    // 這里主要就是配置Web 容器服務,如這里使用的Tomcat
    // 注意該類實現了ErrorPageRegistry ,那么也就是說該類可以用來注冊錯誤頁的
    @Bean
    TomcatServletWebServerFactory tomcatServletWebServerFactory(
      ObjectProvider<TomcatConnectorCustomizer> connectorCustomizers,
      ObjectProvider<TomcatContextCustomizer> contextCustomizers,
      ObjectProvider<TomcatProtocolHandlerCustomizer<?>> protocolHandlerCustomizers) {
      TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
      factory.getTomcatConnectorCustomizers().addAll(connectorCustomizers.orderedStream().collect(Collectors.toList()));
      factory.getTomcatContextCustomizers().addAll(contextCustomizers.orderedStream().collect(Collectors.toList()));
      factory.getTomcatProtocolHandlerCustomizers().addAll(protocolHandlerCustomizers.orderedStream().collect(Collectors.toList()));
      return factory;
    }


  }
}

在@Import中只列出了兩個比較重要的BeanPostProcessorsRegistrar與EmbeddedTomcat

BeanPostProcessorsRegistrar注冊了兩個BeanPostProcessor處理器

public static class BeanPostProcessorsRegistrar implements ImportBeanDefinitionRegistrar, BeanFactoryAware {
  public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
    if (this.beanFactory == null) {
      return;
    }
    registerSyntheticBeanIfMissing(registry, "webServerFactoryCustomizerBeanPostProcessor", WebServerFactoryCustomizerBeanPostProcessor.class, WebServerFactoryCustomizerBeanPostProcessor::new);
    registerSyntheticBeanIfMissing(registry, "errorPageRegistrarBeanPostProcessor", ErrorPageRegistrarBeanPostProcessor.class, ErrorPageRegistrarBeanPostProcessor::new);
  }
}

通過名稱也能知道WebServerFactoryCustomizerBeanPostProcessor用來處理Tomcat相關的自定義信息;ErrorPageRegistrarBeanPostProcessor 這個就是重點了,這個就是用來配置我們的自定義錯誤頁面的。

public class ErrorPageRegistrarBeanPostProcessor implements BeanPostProcessor, BeanFactoryAware {
  @Override
  public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
    // 這里判斷了當前的bean對象是否是ErrorPageRegistry的實例
    // 當前類既然是BeanPostProcessor實例,同時上面注冊了一個TomcatServletWebServerFactory Bean實例
    // 那么在實例化TomcatServletWebServerFactory時一定是會調用該BeanPostProcessor處理器的
    if (bean instanceof ErrorPageRegistry) {
      postProcessBeforeInitialization((ErrorPageRegistry) bean);
    }
    return bean;
  }
  // 注冊錯誤頁面
  private void postProcessBeforeInitialization(ErrorPageRegistry registry) {
    for (ErrorPageRegistrar registrar : getRegistrars()) {
      registrar.registerErrorPages(registry);
    }
  }
  private Collection<ErrorPageRegistrar> getRegistrars() {
    if (this.registrars == null) {
      // Look up does not include the parent context
      // 從當前上下文中(比包括父上下文)查找ErrorPageRegistrar Bean對象
      this.registrars = new ArrayList<>(this.beanFactory.getBeansOfType(ErrorPageRegistrar.class, false, false).values());
      this.registrars.sort(AnnotationAwareOrderComparator.INSTANCE);
      this.registrars = Collections.unmodifiableList(this.registrars);
    }
    return this.registrars;
  }
}

注冊錯誤頁面

在上一步中知道了錯誤頁的注冊入口是在一個ErrorPageRegistrarBeanPostProcessor Bean后處理器中進行注冊的,接下來繼續深入查看這個錯誤頁是如何被注冊的。

接著上一步在ErrorPageRegistrarBeanPostProcessor中查找ErrorPageRegistrar類型的Bean對象。在另外一個自動配置中(ErrorMvcAutoConfiguration)有注冊ErrorPageRegistrar Bean對象

@AutoConfigureBefore(WebMvcAutoConfiguration.class)
@EnableConfigurationProperties({ ServerProperties.class, WebMvcProperties.class })
public class ErrorMvcAutoConfiguration {
  
  // 該類是ErrorPageRegistrar子類,那么在注冊錯誤頁的時候注冊的就是該類中生成的錯誤頁信息
  static class ErrorPageCustomizer implements ErrorPageRegistrar, Ordered {
    private final ServerProperties properties;
    private final DispatcherServletPath dispatcherServletPath;
    protected ErrorPageCustomizer(ServerProperties properties, DispatcherServletPath dispatcherServletPath) {
      this.properties = properties;
      this.dispatcherServletPath = dispatcherServletPath;
    }
    @Override
    public void registerErrorPages(ErrorPageRegistry errorPageRegistry) {
      // 錯誤頁的地址可以在配置文件中自定義server.error.path進行配置,默認:/error
      ErrorPage errorPage = new ErrorPage(this.dispatcherServletPath.getRelativePath(this.properties.getError().getPath()));
      errorPageRegistry.addErrorPages(errorPage);
    }
    @Override
    public int getOrder() {
      return 0;
    }
  }


}

關鍵代碼

//  errorPageRegistry對象的實例是TomcatServletWebServerFactory 
errorPageRegistry.addErrorPages(errorPage);

TomcatServletWebServerFactory中注冊錯誤頁信息,該類的父類(AbstractConfigurableWebServerFactory)方法中有添加錯誤也的方法

public abstract class AbstractConfigurableWebServerFactory {
  private Set<ErrorPage> errorPages = new LinkedHashSet<>();
  public void addErrorPages(ErrorPage... errorPages) {
    this.errorPages.addAll(Arrays.asList(errorPages));
  }
}

這個錯誤頁的注冊到Tomcat容器中又是如何實現的呢?

Tomcat中注冊錯誤頁

接下來看看這個錯誤頁是如何與Tomcat關聯在一起的。

Spring容器最核心的方法是refresh方法

public abstract class AbstractApplicationContext {
  public void refresh() {
    // ...
    // Initialize other special beans in specific context subclasses.
    onRefresh();
    // ...
  }
}

執行onRefresh方法

public class ServletWebServerApplicationContext extends GenericWebApplicationContext {
  protected void onRefresh() {
    super.onRefresh();
    try {
      // 創建Tomcat服務
      createWebServer();
    } catch (Throwable ex) {
      throw new ApplicationContextException("Unable to start web server", ex);
    }
  }
  private void createWebServer() {
    // ...
    // 返回應用于創建嵌入的Web服務器的ServletWebServerFactory。默認情況下,此方法在上下文本身中搜索合適的bean。
    // 在上面ServletWebServerFactoryAutoConfiguration自動配置中,已經自動的根據當前的環境創建了TomcatServletWebServerFactory對象
    ServletWebServerFactory factory = getWebServerFactory();
    // 獲取WebServer實例, factory = TomcatServletWebServerFactory
    this.webServer = factory.getWebServer(getSelfInitializer());
    // ...
  }
}

調用TomcatServletWebServerFactory#getWebServer方法

public class TomcatServletWebServerFactory extends AbstractServletWebServerFactory {
  public WebServer getWebServer(ServletContextInitializer... initializers) {
    // ...
    Tomcat tomcat = new Tomcat();
    // ...
    // 預處理上下文
    prepareContext(tomcat.getHost(), initializers);
    return getTomcatWebServer(tomcat);
  }
  protected void prepareContext(Host host, ServletContextInitializer[] initializers) {
    // ...
    // 配置上下文
    configureContext(context, initializersToUse);
  }
  protected void configureContext(Context context, ServletContextInitializer[] initializers) {
    TomcatStarter starter = new TomcatStarter(initializers);
    // ...
    // 在這里就將錯誤的頁面注冊到了tomcat容器中
    for (ErrorPage errorPage : getErrorPages()) {
      org.apache.tomcat.util.descriptor.web.ErrorPage tomcatErrorPage = new org.apache.tomcat.util.descriptor.web.ErrorPage();
      tomcatErrorPage.setLocation(errorPage.getPath());
      tomcatErrorPage.setErrorCode(errorPage.getStatusCode());
      tomcatErrorPage.setExceptionType(errorPage.getExceptionName());
      context.addErrorPage(tomcatErrorPage);
    }
    // ...
  }
}

到此你就知道了一個錯誤的頁是如何在Springboot中被注冊的。到目前為止我們看到的注冊到tomcat容器中的錯誤頁都是個地址,比如:默認是/error。那這個默認的/error又是怎么提供的接口呢?

默認錯誤頁

在Springboot中默認有個自動配置的錯誤頁,在上面有一個代碼片段你應該注意到了

@AutoConfigureBefore(WebMvcAutoConfiguration.class)
@EnableConfigurationProperties({ ServerProperties.class, WebMvcProperties.class })
public class ErrorMvcAutoConfiguration {
  @Bean
  @ConditionalOnMissingBean(value = ErrorAttributes.class, search = SearchStrategy.CURRENT)
  public DefaultErrorAttributes errorAttributes() {
    return new DefaultErrorAttributes();
  }
  @Bean
  @ConditionalOnMissingBean(value = ErrorController.class, search = SearchStrategy.CURRENT)
  public BasicErrorController basicErrorController(ErrorAttributes errorAttributes, ObjectProvider<ErrorViewResolver> errorViewResolvers) {
    return new BasicErrorController(errorAttributes, this.serverProperties.getError(), errorViewResolvers.orderedStream().collect(Collectors.toList()));
  }
}

查看這個Controller

// 默認的錯誤頁地址是/error
@Controller
@RequestMapping("${server.error.path:${error.path:/error}}")
public class BasicErrorController extends AbstractErrorController {
  
  @RequestMapping(produces = MediaType.TEXT_HTML_VALUE)
  public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
    HttpStatus status = getStatus(request);
    Map<String, Object> model = Collections.unmodifiableMap(getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.TEXT_HTML)));
    response.setStatus(status.value());
    ModelAndView modelAndView = resolveErrorView(request, response, status, model);
    return (modelAndView != null) ? modelAndView : new ModelAndView("error", model);
  }


  @RequestMapping
  public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
    HttpStatus status = getStatus(request);
    if (status == HttpStatus.NO_CONTENT) {
      return new ResponseEntity<>(status);
    }
    Map<String, Object> body = getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.ALL));
    return new ResponseEntity<>(body, status);
  }


}

這里有兩個方法,分別處理了不同的Accept請求頭。到此你是否真正地明白了Springboot中的錯誤處理的工作原理呢?

責任編輯:武曉燕 來源: Spring全家桶實戰案例源碼
相關推薦

2018-09-02 15:43:56

Python代碼編程語言

2021-08-30 07:49:33

索引ICP Mysql

2024-08-02 16:31:12

2023-09-08 08:23:29

Servlet程序MVC

2023-11-30 08:32:31

OpenFeign工具

2024-09-06 17:55:27

Springboot開發

2021-06-03 08:05:46

VSCode 代碼高亮原理前端

2010-08-29 21:09:57

DHCP協議

2023-11-15 08:22:42

Java開發小技巧

2020-06-12 09:20:33

前端Blob字符串

2020-07-28 08:26:34

WebSocket瀏覽器

2024-01-26 06:26:42

Linuxfzf工具

2018-05-17 09:32:52

混合云云計算IT

2024-10-05 00:00:00

HTTPS性能HTTP/2

2017-03-13 10:35:10

JavaScript錯誤調用棧

2024-06-20 08:06:30

2022-04-24 16:00:15

LinuxLinux命令ls命令

2023-12-13 08:28:07

2021-07-14 11:25:12

CSSPosition定位

2010-08-23 09:56:09

Java性能監控
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 精品视频999 | 亚洲精品日韩欧美 | 国产视频福利在线观看 | 久久国产免费看 | 精品1区2区 | 国内91在线 | 国产亚洲网站 | 国产超碰人人爽人人做人人爱 | 黑人精品欧美一区二区蜜桃 | 玖玖玖在线| 成人免费淫片aa视频免费 | 色屁屁在线观看 | 久久精彩视频 | 日本精品视频一区二区 | 成年男女免费视频网站 | 亚洲国产中文字幕 | 中文字幕av在线 | 四虎影院免费在线 | 欧美精品一级 | 欧美日韩在线观看一区 | 亚洲午夜小视频 | 成人av在线大片 | 国产一区二区三区视频 | 亚洲精精品 | 91热爆在线观看 | 欧美日韩三级 | 日韩一区二区三区av | 狠狠干网站| 精品一区二区三区四区 | 欧美日韩最新 | 精品国产99 | 久久久.com | 欧美中文字幕一区二区三区亚洲 | 国产精品视频二区三区 | 日韩精品成人一区二区三区视频 | 亚洲国产欧美精品 | 999精品网 | 另类一区 | 亚洲欧美少妇 | 99精品一区二区三区 | 日韩欧美国产精品一区二区 |