要自定义错误页面并返回相应的错误码,你可以按照以下步骤进行操作:

  1. 创建一个自定义错误页面,比如'404.html'。将该页面放置在 Spring Boot 项目的'src/main/resources/templates' 目录下。

  2. 在 Spring Boot 的配置文件('application.properties' 或 'application.yml')中,添加以下配置:

spring.mvc.throw-exception-if-no-handler-found=true spring.resources.add-mappings=false server.error.whitelabel.enabled=false


这些配置将禁用 Spring Boot 的默认错误处理机制。

3. 创建一个自定义的错误处理类,实现'ErrorController' 接口。例如:

```java
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class CustomErrorController implements ErrorController {

    @RequestMapping("/error")
    public String handleError(HttpServletRequest request) {
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        if (statusCode == HttpStatus.NOT_FOUND.value()) {
            return "404"; // 返回自定义的 404 页面
        } else if (statusCode == HttpStatus.INTERNAL_SERVER_ERROR.value()) {
            return "500"; // 返回自定义的 500 页面
        }
        return "error"; // 返回其他错误页面
    }

    @Override
    public String getErrorPath() {
        return "/error";
    }
}

该类将根据错误码返回相应的错误页面。

  1. 运行 Spring Boot 应用程序,访问一个不存在的页面,应该会返回自定义的 404 页面,并且页面的 HTTP 状态码为 404。

请注意,以上代码中的页面名称(例如'404.html')应与你实际创建的页面名称相匹配。

Spring Boot 3.1.2 自定义错误页面并返回错误码:404 示例

原文地址: https://www.cveoy.top/t/topic/fFx6 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录