1.第一种方式:如果项目使用了templates模版,直接在模版目录下写error.html即可,无需其他配置
2.第二种方式:通过controller指定404页面
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class ErrorUrlController implements ErrorController {
public ErrorUrlController() {}
@RequestMapping("/error")
public String error() {
return "404.html";
}
}
3.第三种方式:实现ErrorPageRegistrar方法
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 有两个参数
* 参数1 响应状态码 NOT_FOUND 404 INTERNAL_SERVER_ERROR 500
* 参数2 出现响应状态码的时候的跳转路径 可以自定义跳转路径
*/
ErrorPage error404 = new ErrorPage(HttpStatus.NOT_FOUND, "/html/404.html");
ErrorPage error500 = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/html/500.html");
/**
* 将ErrorPage 注册到注册器中
*/
registry.addErrorPages(error404,error500);
}
}
参考文档:https://segmentfault.com/a/1190000021996691
https://blog.csdn.net/liangshui999/article/details/105292437/