接着前面几篇web处理请求的博文,本文将说明,当出现异常的场景下,如404请求url不存在,,403无权,500服务器异常时,我们可以如何处理

原文友链: SpringBoot系列教程web篇之404、500异常页面配置

I. 环境搭建

首先得搭建一个web应用才有可能继续后续的测试,借助SpringBoot搭建一个web应用属于比较简单的活;

创建一个maven项目,pom文件如下

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.7</version>
<relativePath/> <!-- lookup parent from update -->
</parent> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring-cloud.version>Finchley.RELEASE</spring-cloud.version>
<java.version>1.8</java.version>
</properties> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.45</version>
</dependency>
</dependencies> <build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</pluginManagement>
</build>
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>

依然是一般的流程,pom依赖搞定之后,写一个程序入口

/**
* Created by @author yihui in 15:26 19/9/13.
*/
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class);
}
}

II. 异常页面配置

在SpringBoot项目中,本身提供了一个默认的异常处理页面,当我们希望使用自定义的404,500等页面时,可以如何处理呢?

1. 默认异常页面配置

在默认的情况下,要配置异常页面非常简单,在资源路径下面,新建 error 目录,在下面添加400.html, 500html页面即可

项目结构如上,注意这里的实例demo是没有使用模板引擎的,所以我们的异常页面放在static目录下;如果使用了如FreeMaker模板引擎时,可以将错误模板页面放在template目录下

接下来实际测试下是否生效, 我们先定义一个可能出现服务器500的服务

@Controller
@RequestMapping(path = "page")
public class ErrorPageRest { @ResponseBody
@GetMapping(path = "divide")
public int divide(int sub) {
System.out.println("divide1");
return 1000 / sub;
}
}

请求一个不存在的url,返回我们定义的400.html页面

<html>
<head>
<title>404页面</title>
</head>
<body>
<h3>页面不存在</h3>
</body>
</html>

请求一个服务器500异常,返回我们定义的500.html页面

<html>
<head>
<title>500页面</title>
</head>
<body>
<h2 style="color: red;">服务器出现异常!!!</h2>
</body>
</html>

2. BasicErrorController

看上面的使用比较简单,自然会有个疑问,这个异常页面是怎么返回的呢?

从项目启动的日志中,注意一下RequestMappingHandlerMapping

可以发现里面有个/error的路径不是我们自己定义的,从命名上来看,这个多半就是专门用来处理异常的Controller -> BasicErrorController, 部分代码如下

@Controller
@RequestMapping("${server.error.path:${error.path:/error}}")
public class BasicErrorController extends AbstractErrorController { @Override
public String getErrorPath() {
return this.errorProperties.getPath();
} @RequestMapping(produces = "text/html")
public ModelAndView errorHtml(HttpServletRequest request,
HttpServletResponse response) {
HttpStatus status = getStatus(request);
Map<String, Object> model = Collections.unmodifiableMap(getErrorAttributes(
request, isIncludeStackTrace(request, MediaType.TEXT_HTML)));
response.setStatus(status.value());
ModelAndView modelAndView = resolveErrorView(request, response, status, model);
return (modelAndView != null) ? modelAndView : new ModelAndView("error", model);
} @RequestMapping
@ResponseBody
public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
Map<String, Object> body = getErrorAttributes(request,
isIncludeStackTrace(request, MediaType.ALL));
HttpStatus status = getStatus(request);
return new ResponseEntity<>(body, status);
}
}

这个Controller中,一个返回网页的接口,一个返回Json串的接口;我们前面使用的应该是第一个,那我们什么场景下会使用到第二个呢?

  • 通过制定请求头的Accept,来限定我们只希望获取json的返回即可

3. 小结

本篇内容比较简单,归纳为两句话如下

  • 将自定义的异常页面根据http状态码命名,放在/error目录下
  • 在异常状况下,根据返回的http状态码找到对应的异常页面返回

II. 其他

0. 项目

a. 系列博文

b. 项目源码

1. 一灰灰Blog

尽信书则不如,以上内容,纯属一家之言,因个人能力有限,难免有疏漏和错误之处,如发现bug或者有更好的建议,欢迎批评指正,不吝感激

下面一灰灰的个人博客,记录所有学习和工作中的博文,欢迎大家前去逛逛

SpringBoot系列教程web篇之404、500异常页面配置的更多相关文章

  1. SpringBoot系列教程web篇之过滤器Filter使用指南扩展篇

    前面一篇博文介绍了在 SpringBoot 中使用 Filter 的两种使用方式,这里介绍另外一种直接将 Filter 当做 Spring 的 Bean 来使用的方式,并且在这种使用方式下,Filte ...

  2. SpringBoot系列教程Web篇之开启GZIP数据压缩

    本篇可以归纳在性能调优篇,虽然内容非常简单,但效果可能出乎预料的好: 分享一个真实案例,我们的服务部署在海外,国内访问时访问服务时,响应有点夸张:某些返回数据比较大的接口,耗时在 600ms+上,然而 ...

  3. SpringBoot系列教程web篇Listener四种注册姿势

    java web三要素Filter, Servlet前面分别进行了介绍,接下来我们看一下Listener的相关知识点,本篇博文主要内容为SpringBoot环境下,如何自定义Listener并注册到s ...

  4. SpringBoot系列教程web篇Servlet 注册的四种姿势

    原文: 191122-SpringBoot系列教程web篇Servlet 注册的四种姿势 前面介绍了 java web 三要素中 filter 的使用指南与常见的易错事项,接下来我们来看一下 Serv ...

  5. SpringBoot系列教程web篇之过滤器Filter使用指南

    web三大组件之一Filter,可以说是很多小伙伴学习java web时最早接触的知识点了,然而学得早不代表就用得多.基本上,如果不是让你从0到1写一个web应用(或者说即便从0到1写一个web应用) ...

  6. SpringBoot系列教程web篇之自定义异常处理HandlerExceptionResolver

    关于Web应用的全局异常处理,上一篇介绍了ControllerAdvice结合@ExceptionHandler的方式来实现web应用的全局异常管理: 本篇博文则带来另外一种并不常见的使用方式,通过实 ...

  7. SpringBoot系列教程web篇之全局异常处理

    当我们的后端应用出现异常时,通常会将异常状况包装之后再返回给调用方或者前端,在实际的项目中,不可能对每一个地方都做好异常处理,再优雅的代码也可能抛出异常,那么在 Spring 项目中,可以怎样优雅的处 ...

  8. SpringBoot系列教程web篇之重定向

    原文地址: SpringBoot系列教程web篇之重定向 前面介绍了spring web篇数据返回的几种常用姿势,当我们在相应一个http请求时,除了直接返回数据之外,还有另一种常见的case -&g ...

  9. SpringBoot系列教程web篇之Get请求参数解析姿势汇总

    一般在开发web应用的时候,如果提供http接口,最常见的http请求方式为GET/POST,我们知道这两种请求方式的一个显著区别是GET请求的参数在url中,而post请求可以不在url中:那么一个 ...

随机推荐

  1. C++编译器与链接器工作原理

    http://blog.csdn.net/success041000/article/details/6714195 1. 几个概念 1)编译:把源文件中的源代码翻译成机器语言,保存到目标文件中.如果 ...

  2. 浙大PAT 2-10. 海盗分赃——经典博弈

    题意 P个海盗偷了D颗钻石后分赃($3 \leq P, D\leq 100$),采用分赃策略: 从1号开始,提出一个分配金币的方案,如果能够得到包括1号在内的绝对多数(即大于半数)同意,则执行该方案, ...

  3. Codeforces Round #552 (Div. 3)-D-Walking Robot-(贪心)

    http://codeforces.com/contest/1154/problem/D 解题: 1.无光的时候优先使用太阳能电池. 2.有光的时候 (1)太阳能电池没满电,让它充,使用普通电池 (2 ...

  4. C++ auto 完成类型自动推导与使用

    c++11 允许声明一个变量或对象(object)而不需要指明其类型,只需说明它是auto. 1.如: auto i = 42: //i是整型 double   f(); auto d=f(); // ...

  5. 清华大学&中国人工智能学会:2019人工智能发展报告

    2019年11月30日,2019中国人工智能产业年会重磅发布<2019人工智能发展报告>(Report of Artificial Intelligence Development 201 ...

  6. UFUN函数UF_MODL UF_DISP UF_OBJ(name_switch) ( UF_DISP_ask_name_display_status、UF_DISP_set_name_display_status)

    /* TODO: Add your application code here */ /* 此程序主要演示的是name_switch (设置名称显示) */ UF_initialize(); //MO ...

  7. docker安装 与 基本配置

    1.安装docker #yum remove docker \ docker-common \ container-selinux \ docker-selinux \ docker-engine \ ...

  8. 声源定位之2精读《sound localization based on phase difference enhancement using deep neuarl networks》

    2.1.1 题目与摘要 1.为什么要增强IPD? The phase differences between the discrete Fourier transform (DFT) coeffici ...

  9. stream_context_create解析

    (PHP 4 >= 4.3.0, PHP 5, PHP 7) stream_context_create — 创建资源流上下文 说明¶ stream_context_create ([ arra ...

  10. How to Install Ruby on CentOS/RHEL 7/6

    How to Install Ruby on CentOS/RHEL 7/6 . Ruby is a dynamic, object-oriented programming language foc ...