栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springboot异常处理机制之自定义404、500错误提示页面

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springboot异常处理机制之自定义404、500错误提示页面

目录
  • `springboot` 自定义 `404、500` 错误页面
    • `springboot` 默认的异常处理机制
    • 使用模板引擎
      • 使用示例
        • 创建 `springboot` 项目如下
        • `application.properties` 项目配置文件
        • `404` 页面内容如下
        • `500` 页面内容如下
        • `controller` 如下
        • `404.html` 页面测试
        • `500.html` 页面测试
    • 没有使用模板引擎

springboot 自定义 404、500 错误页面 springboot 默认的异常处理机制

springboot 默认已经提供了一套处理异常的机制。一旦程序中出现了异常 springboot 会向 /error 的 url 发送请求。在 springboot 中提供了一个名为 BasicErrorController 的类来处理 /error 请求,然后跳转到默认显示异常的页面来展示异常信息

使用模板引擎

在使用 thymeleaf 等模板引擎时,springboot 会自动到 src/main/resources/templates/error/,文件夹下寻找 404.html、500.html 的错误提示页面

错误提示页面的命名规则就是:错误码.html,如 404 是 404.html,500 是 500.html

使用示例 创建 springboot 项目如下

404、500 错误提示页面结构如下

application.properties 项目配置文件
server.port=8080

#它的默认值就是classpath:/templates/,源码在ThymeleafProperties类中
spring.mvc.view.prefix=classpath:/templates/
#它的默认值就是.html,源码在ThymeleafProperties类中
spring.mvc.view.suffix=.html
spring.thymeleaf.cache=false
404 页面内容如下



    
    404
    
    


	


500 页面内容如下



    
    500
    
    


    


controller 如下
@Controller
public class PageController {

    // 跳转到登录页
    @GetMapping(path = "/toLogin")
    public String toLogin() {
        int code = 1/0;
        return "login";
    }
}
404.html 页面测试

访问不存在的接口:http://localhost:8080/aaaa,结果如下

500.html 页面测试

访问已存在的接口:http://localhost:8080/toLogin,结果如下

没有使用模板引擎

如果没有使用 thymeleaf 等模板引擎时,springboot 会到静态资源文件夹寻找 404.htm、500.html的错误提示页面,命名同上。springboot 中默认的静态资源路径有 4 个,分别是

  • classpath:/metaINF/resources/
  • classpath:/resources/
  • classpath:/static/
  • classpath:/public/

优先级顺序为:meta-INF/resources > resources > static > public,以上 4 种路径创建 error 文件夹,再创建 404、500 错误提示页面如下


不用写额外的映射器,就能直接请求到

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/605445.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号