配置一个统一的静态页面,将400、403、404、500等常见报错重定向到该静态页面,而不是抛出异常
时间: 2024-01-13 18:05:40 浏览: 31
可以使用Spring Boot提供的ErrorController来实现将常见错误重定向到统一的静态页面,具体步骤如下:
1. 创建一个Controller类,实现ErrorController接口,并在类上加上@Controller注解。
2. 在类中实现getErrorPath()方法,返回一个固定的错误路径(比如/error)。
3. 在类中实现一个方法,用于处理错误请求,并在方法中做重定向到统一的静态页面。
示例代码如下:
```java
@Controller
public class MyErrorController implements ErrorController {
@Override
public String getErrorPath() {
return "/error";
}
@RequestMapping("/error")
public String handleError(HttpServletRequest request) {
Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
if (status != null) {
Integer statusCode = Integer.valueOf(status.toString());
if (statusCode == HttpStatus.NOT_FOUND.value()) {
return "redirect:/404.html";
} else if (statusCode == HttpStatus.FORBIDDEN.value()) {
return "redirect:/403.html";
} else if (statusCode == HttpStatus.INTERNAL_SERVER_ERROR.value()) {
return "redirect:/500.html";
} else if (statusCode == HttpStatus.BAD_REQUEST.value()) {
return "redirect:/400.html";
}
}
return "redirect:/error.html";
}
}
```
上述代码中,当请求出现错误时,会通过getErrorPath()方法返回的路径进入到handleError()方法中进行处理。在handleError()方法中,根据不同的错误类型进行重定向到对应的静态页面。如果错误类型未知,则重定向到统一的错误页面。
注意:需要在pom.xml文件中添加以下依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
```
因为重定向到静态页面需要使用Thymeleaf模板引擎解析页面,需要添加该依赖才能正常解析页面。如果不需要使用Thymeleaf,可以将该依赖注释掉或者删除。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)