You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何在Spring Boot控制器类中添加404页面未找到功能?

在Spring Boot中实现404错误页面的几种方式

当然可以在Spring Boot控制器类中添加404页面未找到的处理逻辑,而且有多种实现方案,我给你逐一说明:

1. 直接通过静态/模板页面自动匹配(最简便)

Spring Boot默认支持根据HTTP状态码自动映射错误页面,你只需要按规则放置页面即可:

  • 静态HTML页面:在src/main/resources/static/error/目录下创建404.html
  • 模板页面(如Thymeleaf、Freemarker):在src/main/resources/templates/error/目录下创建404.html

当用户访问不存在的URL时,Spring Boot会自动返回这个页面,无需编写任何Java代码。

2. 在控制器中添加全局匹配路由

你提到的在控制器中添加方法匹配未识别URL的方式完全可行,通过@RequestMapping("/**")来捕获所有未被其他路由匹配的请求:

@Controller
public class NotFoundController {

    // 注意:/**会匹配所有请求,但Spring路由匹配遵循"精确优先"原则,所以不会影响已有路由
    @RequestMapping("/**")
    public String handleNotFound() {
        // 返回你的404模板路径,对应templates/error/404.html
        return "error/404";
    }
}

注意:如果你的应用中有其他更精确的路由(比如/user/product),它们会优先被匹配,只有当没有任何路由能匹配请求时,这个方法才会触发。

3. 自定义ErrorController(更灵活的错误处理)

实现Spring Boot的ErrorController接口,可以更灵活地处理不同状态码的错误:

import jakarta.servlet.http.HttpServletRequest;
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;

import javax.servlet.RequestDispatcher;

@Controller
public class CustomErrorController implements ErrorController {

    @RequestMapping("/error")
    public String handleError(HttpServletRequest request) {
        // 获取错误状态码
        Object statusCodeObj = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
        
        if (statusCodeObj != null) {
            int statusCode = Integer.parseInt(statusCodeObj.toString());
            
            // 针对404错误返回对应页面
            if (statusCode == HttpStatus.NOT_FOUND.value()) {
                return "error/404";
            }
            // 还可以扩展处理其他错误码,比如500、403等
            else if (statusCode == HttpStatus.INTERNAL_SERVER_ERROR.value()) {
                return "error/500";
            }
        }
        
        // 默认错误页面
        return "error/default";
    }

    // Spring Boot 2.3及以上版本不需要重写getErrorPath(),可通过配置server.error.path自定义错误路径
}

4. 全局异常捕获(捕获NoHandlerFoundException)

通过@ControllerAdvice全局捕获NoHandlerFoundException,但需要先在配置文件中开启相关配置:

第一步:添加配置(application.properties)

# 当没有找到处理程序时抛出异常
spring.mvc.throw-exception-if-no-handler-found=true
# 禁止Spring Boot自动映射静态资源(避免静态资源请求被误判为404)
spring.web.resources.add-mappings=false

第二步:编写全局异常处理器

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.NoHandlerFoundException;

@ControllerAdvice
public class GlobalErrorHandler {

    @ExceptionHandler(NoHandlerFoundException.class)
    public String handleNotFoundError() {
        return "error/404";
    }
}

总结

你提到的在Spring Boot控制器类中添加404处理逻辑的方式是完全可行的(对应上面的第2、3种方式),而第1种静态页面的方式是最快捷的,适合简单场景;如果需要处理多种错误状态码,第3、4种方式会更灵活。

内容的提问来源于stack exchange,提问作者Charles

火山引擎 最新活动