首先,在你的项目中创建一个文件夹,比如src/main/resources/templates/error
,在该文件夹下编写自定义的错误页面,例如 404.html
和 500.html
。这些页面会在出现相应的错误时被加载显示。
接下来,你需要在Spring Boot应用的配置类中添加配置来设置错误页面的路径。可以创建一个类,如下所示:
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.ErrorPageRegistrar;
import org.springframework.boot.web.server.ErrorPageRegistry;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
@Configuration
public class ErrorConfig implements ErrorPageRegistrar {
@Override
public void registerErrorPages(ErrorPageRegistry registry) {
ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/error/404");
ErrorPage error500Page = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error/500");
registry.addErrorPages(error404Page, error500Page);
}
}
这个配置类通过实现ErrorPageRegistrar
接口,注册了404和500错误页面。在这个例子中,当出现404错误时,会跳转到/error/404
页面;当出现500错误时,会跳转到/error/500
页面。
确保你的404.html
和500.html
页面位于src/main/resources/templates/error
路径下,否则需要根据实际情况修改路径。