1. 程式人生 > 實用技巧 >SpringBoot-09-首頁和錯誤頁定製

SpringBoot-09-首頁和錯誤頁定製

1、首頁定製

  • 在WebMvcAutoConfiguration.class中找到以下程式碼,得出

    自定義一個index.html,放在靜態資源目錄下,就可以實現首頁定製

    @Bean
    public WelcomePageHandlerMapping welcomePageHandlerMapping(ApplicationContext applicationContext, FormattingConversionService mvcConversionService, ResourceUrlProvider mvcResourceUrlProvider) {
    WelcomePageHandlerMapping welcomePageHandlerMapping = new WelcomePageHandlerMapping(new TemplateAvailabilityProviders(applicationContext), applicationContext, this.getWelcomePage(), this.mvcProperties.getStaticPathPattern());
    welcomePageHandlerMapping.setInterceptors(this.getInterceptors(mvcConversionService, mvcResourceUrlProvider));
    welcomePageHandlerMapping.setCorsConfigurations(this.getCorsConfigurations());
    return welcomePageHandlerMapping;
    }

    //從靜態資源目錄裡獲取 index.html 當作首頁
    private Optional<Resource> getWelcomePage() {
    String[] locations = WebMvcAutoConfiguration.getResourceLocations(this.resourceProperties.getStaticLocations());
    return Arrays.stream(locations).map(this::getIndexHtml).filter(this::isReadable).findFirst();
    }

    private Resource getIndexHtml(String location) {
    return this.resourceLoader.getResource(location + "index.html");
    }

2、錯誤頁定製

  • 在 resources 資料夾下建立 error 資料夾

    • 新建 404.html ,則出現 404 錯誤就會自動跳轉到這個頁面

    • 新建 500.html ,則出現 500 錯誤就會自動跳轉到這個頁面