springboot如何配置404错误页面
时间: 2023-08-09 07:05:33 浏览: 93
Spring Boot提供了默认的404页面,但是您可以通过以下步骤自定义404页面:
1. 创建一个404.html页面,该页面应该放在classpath:/templates/error/目录下。
2. 在application.properties或application.yml文件中添加以下配置:
```
spring.mvc.throw-exception-if-no-handler-found=true
spring.resources.add-mappings=false
```
上述配置将会在没有找到处理请求的控制器时抛出异常,并且禁用静态资源的默认映射。
3. 创建一个自定义的ErrorController,该控制器应该继承BasicErrorController并覆盖getErrorPath()方法,例如:
```java
@Controller
public class CustomErrorController extends BasicErrorController {
public CustomErrorController(ErrorAttributes errorAttributes) {
super(errorAttributes);
}
@Override
public String getErrorPath() {
return "/error";
}
@RequestMapping("/error")
public ModelAndView error(HttpServletRequest request, HttpServletResponse response) {
ModelAndView modelAndView = new ModelAndView("error/404");
modelAndView.setStatus(HttpStatus.NOT_FOUND);
return modelAndView;
}
}
```
上述代码将会创建一个自定义的ErrorController用于处理404错误,并返回自定义的404页面。需要注意的是,getErrorPath()方法应该返回与@RequestMapping注解中的路径相同的路径。
完成以上步骤后,您就可以访问自定义的404页面了。
阅读全文
相关推荐
















