Spring Boot 3.x 自定义 404 页面 (无需 Thymeleaf)

在 Spring Boot 应用中,自定义 404 页面可以让用户体验更加友好。本文将介绍如何在 不使用 Thymeleaf 的情况下,在 Spring Boot 3.1.2 中自定义 404 页面。

步骤

  1. 创建自定义错误处理器:

    
    @Controller   public class CustomErrorController implements ErrorController {
    
        @RequestMapping('/error')       public String handleError() {           // 处理 404 错误,返回自定义的 404 页面           return '404';        }
    
        @Override       public String getErrorPath() {           // 返回错误路径           return '/error';        }   }   ```
    
    
  2. 创建 404 页面:

    resources/templates 目录下创建名为 404.html 的文件,并编写自定义的 404 页面内容。

  3. 配置 Spring Boot 应用:

    在 Spring Boot 应用的配置类中添加以下配置:

    
    @Configuration   @Import(ErrorMvcAutoConfiguration.class)   public class CustomErrorConfiguration {   }   ```
    
    **注意**: 
    
    -  确保你的视图解析器配置正确,以便正确解析 `404.html` 页面。   -  上述代码中的 `'404'` 指的是 `resources/templates` 目录下的 `404.html` 文件。你需要根据实际情况修改文件名或路径。
    
    

通过以上步骤,当发生 404 错误时,你的 Spring Boot 应用将会返回自定义的 404 页面。

优势

  • 不需要依赖 Thymeleaf 等模板引擎,更加轻量级。- 可以自由选择视图解析技术,例如 JSP、Freemarker 等。- 代码简洁易懂,方便维护。

希望本文能够帮助你在 Spring Boot 3.x 中轻松自定义 404 页面!

SpringBoot 3.x 自定义404页面:无需Thymeleaf

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

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