在项目中我们遇到404找不到的错误、或者500服务器错误都需要配置相应的页面给用户一个友好的提示,而在Spring Boot中我们需要如何设置。
建议先参考https://blog.csdn.net/qq_37142346/article/details/79879643
https://blog.csdn.net/sihai12345/article/details/81220781,了解异常的底层机制
我们需要实现ErrorController接口,重写handleError方法。
package com.liqiang.demo.controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
class MainsiteErrorController implements ErrorController {
@RequestMapping("/error")
public String handleError(HttpServletRequest request){
//获取statusCode:401,404,500
Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
if(statusCode == 401)
{
return "/401";
}
else if(statusCode == 404)
{
return "/404";
}
else if(statusCode == 403)
{
return "/403";
}
else
{
return "/500";
}
}
@Override
public String getErrorPath() {
return "/error";
}
}
这里我只测试了404,首先在templates下建一个404页面。然后在浏览器输入一个不存在的地址