SpringBoot异常处理机制之自定义40500错误提示页面 - 518篇
import org.springframework.boot.web.server.ConfigurableWebServerFactory;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
@Configuration
public class ErrorPageConfig {
@Bean
public ConfigurableServletWebServerFactory servletWebServerFactory() {
ConfigurableServletWebServerFactory factory = new TomcatServletWebServerFactory();
factory.setErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/error-404.html"),
new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error-500.html"));
return factory;
}
@Bean
public SimpleUrlHandlerMapping customErrorPages() {
SimpleUrlHandlerMapping handlerMapping = new SimpleUrlHandlerMapping();
Properties mappings = new Properties();
mappings.setProperty("/**/favicon.ico", "faviconFallback");
handlerMapping.setUrlMap(mappings);
return handlerMapping;
}
@Bean(name = "faviconFallback")
public SimpleControllerHandlerAdapter faviconFallback() {
return new SimpleControllerHandlerAdapter((request, response) -> {
Resource favicon = new ClassPathResource("/static/images/favicon.ico"); // 确保路径正确
if (favicon.exists()) {
// 将favicon文件写入响应流
try (InputStream inputStream = favicon.getInputStream()) {
FileCopyUtils.copy(inputStream, response.getOutputStream());
} catch (IOException e) {
throw new RuntimeException("Failed to write favicon", e);
}
} else {
// 如果文件不存在,可以选择其他策略,比如返回默认favicon或者空响应
// ...
}
});
}
}
这个代码示例展示了如何在Spring Boot应用中配置自定义的错误页面,以及如何处理favicon.ico文件缺失的情况。通过使用ErrorPage
和SimpleUrlHandlerMapping
,我们可以为404和500错误指定自定义页面,同时提供了一个示例来处理favicon.ico文件的回退。
评论已关闭