You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何替换嵌入式Tomcat中“未找到对应网页”的提示信息?

自定义嵌入式Tomcat的404错误提示(Spring Boot 1.3.3 + Web MVC 4.2.5)

嘿,针对你用Spring Boot 1.3.3(嵌入式Tomcat)搭配Spring Web MVC 4.2.5的场景,要替换默认的404提示信息,我给你整理了几种靠谱的实现方式,按需选就行:

方法1:自定义ErrorController(最灵活的动态处理)

Spring Boot默认用BasicErrorController处理错误请求,我们可以自己实现ErrorController接口,完全掌控错误响应的内容。

示例代码(返回JSON格式)

如果需要返回自定义JSON提示,用@RestController:

import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
public class CustomErrorController implements ErrorController {

    private static final String ERROR_PATH = "/error";

    @RequestMapping(value = ERROR_PATH)
    public Map<String, Object> handleError(HttpServletRequest request) {
        Map<String, Object> response = new HashMap<>();
        // 获取请求状态码和路径
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        String requestUri = (String) request.getAttribute("javax.servlet.error.request_uri");
        
        if (statusCode == 404) {
            response.put("code", 404);
            response.put("message", String.format("抱歉,你访问的路径「%s」不存在", requestUri));
        } else {
            response.put("code", statusCode);
            response.put("message", "服务器临时故障,请稍后再试");
        }
        return response;
    }

    @Override
    public String getErrorPath() {
        return ERROR_PATH;
    }
}

示例代码(返回模板视图)

如果用Thymeleaf等模板引擎,换成@Controller返回视图:

import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

@Controller
public class CustomErrorController implements ErrorController {

    private static final String ERROR_PATH = "/error";

    @RequestMapping(value = ERROR_PATH)
    public ModelAndView handleError(HttpServletRequest request) {
        ModelAndView mv = new ModelAndView();
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        String requestUri = (String) request.getAttribute("javax.servlet.error.request_uri");
        
        if (statusCode == 404) {
            mv.addObject("requestUri", requestUri);
            mv.setViewName("error/404"); // 对应templates/error/404.html模板
        } else {
            mv.setViewName("error/5xx");
        }
        return mv;
    }

    @Override
    public String getErrorPath() {
        return ERROR_PATH;
    }
}

方法2:全局异常处理器(针对404异常)

Spring MVC默认不会抛出路径找不到的异常,需要先开启配置,再用全局异常处理器捕获处理。

步骤1:开启NoHandlerFoundException

创建Web配置类,开启抛出路径未找到的异常:

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import javax.servlet.ServletRegistration;

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void configureDispatchServlet(ServletRegistration.Dynamic registration) {
        // 关键:开启路径未找到时抛出异常
        registration.setInitParameter("throwExceptionIfNoHandlerFound", "true");
    }
}

步骤2:全局捕获404异常

创建全局异常处理类,用@RestControllerAdvice(或@ControllerAdvice)处理:

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

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(NoHandlerFoundException.class)
    public Map<String, Object> handle404Error(NoHandlerFoundException e, HttpServletRequest request) {
        Map<String, Object> response = new HashMap<>();
        response.put("code", 404);
        response.put("message", String.format("自定义提示:页面「%s」不存在", request.getRequestURI()));
        return response;
    }
}

方法3:自定义静态错误页面(简单直接)

如果只需要静态HTML提示,直接配置Tomcat映射错误页面即可。

步骤1:配置Tomcat错误页面映射

创建配置类注册EmbeddedServletContainerCustomizer:

import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class TomcatErrorConfig {

    @Bean
    public EmbeddedServletContainerCustomizer containerCustomizer() {
        return container -> {
            if (container instanceof TomcatEmbeddedServletContainerFactory) {
                TomcatEmbeddedServletContainerFactory tomcatFactory = (TomcatEmbeddedServletContainerFactory) container;
                // 映射404状态码到静态页面
                tomcatFactory.addErrorPages(new org.springframework.boot.context.embedded.ErrorPage(
                        org.springframework.http.HttpStatus.NOT_FOUND, "/404.html"));
            }
        };
    }
}

步骤2:创建静态404页面

在src/main/resources/static目录下创建404.html,内容自定义:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>页面不存在</title>
</head>
<body>
    <h2>😯 哎呀,你找的页面跑丢了!</h2>
    <p>你访问的路径:<span id="currentPath"></span></p>
    <script>
        document.getElementById('currentPath').textContent = window.location.href;
    </script>
</body>
</html>

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:02:24