ps: 推荐一下本人的通用后台管理项目crowd-admin 以及newbee-mall增强版,喜欢的话给个star就好

源码分析

在springboot中默认有一个异常处理器接口ErrorContorller,该接口提供了getErrorPath()方法,此接口的BasicErrorController实现类实现了getErrorPath()方法,如下:


/*
* AbstractErrorController是ErrorContoller的实现类
*/
@Controller
@RequestMapping("${server.error.path:${error.path:/error}}")
public class BasicErrorController extends AbstractErrorController { private final ErrorProperties errorProperties; ...
@Override
public String getErrorPath() {
return this.errorProperties.getPath();
} @RequestMapping(produces = MediaType.TEXT_HTML_VALUE)
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
public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
HttpStatus status = getStatus(request);
if (status == HttpStatus.NO_CONTENT) {
return new ResponseEntity<>(status);
}
Map<String, Object> body = getErrorAttributes(request, isIncludeStackTrace(request, MediaType.ALL));
return new ResponseEntity<>(body, status);
}
....
}

errorProperties类定义如下:

public class ErrorProperties {

	/**
* Path of the error controller.
*/
@Value("${error.path:/error}")
private String path = "/error";
...
}

由此可见,springboot中默认有一个处理/error映射的控制器,有errorerrorHtml两个方法的存在,它可以处理来自浏览器页面和来自机器客户端(app应用)的请求。

当用户请求不存在的url时,dispatcherServlet会交由ResourceHttpRequestHandler映射处理器来处理该请求,并在handlerRequest方法中,重定向至/error映射,代码如下:

	@Override
public void handleRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { // For very general mappings (e.g. "/") we need to check 404 first
Resource resource = getResource(request);
if (resource == null) {
logger.debug("Resource not found");
response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404
return;
}
...
}

getResource(request)会调用this.resolverChain.resolveResource(request, path, getLocations())方法,getLocations()方法返回结果如下:

接着程序会执行到getResource(pathToUse, location)方法如下:

	@Nullable
protected Resource getResource(String resourcePath, Resource location) throws IOException {
// 新建一个resource对象,url为 location + resourcePath,判断此对象(文件)是否存在
Resource resource = location.createRelative(resourcePath);
if (resource.isReadable()) {
if (checkResource(resource, location)) {
return resource;
}
else if (logger.isWarnEnabled()) {
Resource[] allowedLocations = getAllowedLocations();
logger.warn("Resource path \"" + resourcePath + "\" was successfully resolved " +
"but resource \"" + resource.getURL() + "\" is neither under the " +
"current location \"" + location.getURL() + "\" nor under any of the " +
"allowed locations " + (allowedLocations != null ? Arrays.asList(allowedLocations) : "[]"));
}
}
return null;
}

在resource.isReadable()中,程序会在locations目录中寻找path目录下文件,由于不存在,返回null。

最终也就导致程序重定向至/error映射,如果是来自浏览器的请求,也就会返回/template/error/404.html页面,所以对于404请求,只需要在template目录下新建error目录,放入404页面即可。

使用注意

  1. 在springboot4.x中我们可以自定义ControllerAdvice注解 + ExceptionHandler注解来处理不同错误类型的异常,但在springboot中404异常和拦截器异常由spring自己处理。

springboot异常处理之404的更多相关文章

  1. Springboot异常处理和自定义错误页面

    1.异常来源 要处理程序发生的异常,首先需要知道异常来自哪里? 1.前端错误的的请求路径,会使得程序发生4xx错误,最常见的就是404,Springboot默认当发生这种错误的请求路径,pc端响应的页 ...

  2. SpringBoot异常处理统一封装我来做-使用篇

    SpringBoot异常处理统一封装我来做-使用篇 简介 重复功能我来写.在 SpringBoot 项目里都有全局异常处理以及返回包装等,返回前端是带上succ.code.msg.data等字段.单个 ...

  3. nginx反向代理部署springboot项目报404无法加载静态资源

    问题:nginx反向代理部署springboot项目报404无法加载静态资源(css,js,jpg,png...) springboot默认启动端口为8080,如果需要通过域名(不加端口号)直接访问s ...

  4. SpringBoot异常处理(二)

    参数校验机制 JSR-303 Hibernate 参数接收方式: URL路径中的参数 {id} (@PathVariable(name="id") int-whatever) UR ...

  5. 配置springboot在访问404时自定义返回结果以及统一异常处理

    在搭建项目框架的时候用的是springboot,想统一处理异常,但是发现404的错误总是捕捉不到,总是返回的是springBoot自带的错误结果信息. 如下是springBoot自带的错误结果信息: ...

  6. 【使用篇二】SpringBoot异常处理(9)

    异常的处理方式有多种: 自定义错误页面 @ExceptionHandler注解 @ControllerAdvice+@ExceptionHandler注解 配置SimpleMappingExcepti ...

  7. SpringBoot 异常处理

    异常处理最佳实践 根据我的工作经历来看,我主要遵循以下几点: 尽量不要在代码中写try...catch.finally把异常吃掉. 异常要尽量直观,防止被他人误解 将异常分为以下几类,业务异常,登录状 ...

  8. springBoot异常处理

    1.status=404 Whitelabel Error Page Whitelabel Error Page This application has no explicit mapping fo ...

  9. springboot访问请求404问题

    新手在刚接触springboot的时候,可能会出现访问请求404的情况,代码没问题,但就是404. 疑问:在十分确定代码没问题的时候,可以看下自己的包是不是出问题了? 原因:SpringBoot 注解 ...

随机推荐

  1. 题解 P5401 [CTS2019]珍珠

    蒟蒻语 这题太玄学了,蒟蒻写篇题解来让之后复习 = = 蒟蒻解 假设第 \(i\) 个颜色有 \(cnt_i\) 个珍珠. \(\sum\limits_{i=1}^{n} \left\lfloor\f ...

  2. hadoop技术产生

    一.为什么有大数据 我的理解是: 1)数据量达到了传统数据库的瓶颈 2)数据量的激增 3)硬件成本的降低 [ 技术水平的上升 ] 4)想通过大量的数据发现潜在的商业价值 二.什么是大数据 大数据指的是 ...

  3. React Native学习记录

    1.端口问题 在调试的时候,监听的是8081端口.如果被占用,会报错,并且在reload的时候导致app直接崩掉. 2.插件网站收集 https://nativebase.io/ https://js ...

  4. Feign使用注意事项

    使用Feign时,为了不写重复代码,需要写feign公共接口方便调用,这时候需要注意以下问题,以发邮件为例 定义公共接口 /** * @author liuyalong * @date 2020/10 ...

  5. C++ cin.ignore() 的使用

    cin.sync()的功能是清空缓冲区,而cin.ignore()虽然也是删除缓冲区中数据的作用,但其对缓冲区中的删除数据控制的较精确. 有时候你只想取缓冲区的一部分,而舍弃另一部分,这是就可以使用c ...

  6. Spark SQL 小文件问题处理

    在生产中,无论是通过SQL语句或者Scala/Java等代码的方式使用Spark SQL处理数据,在Spark SQL写数据时,往往会遇到生成的小文件过多的问题,而管理这些大量的小文件,是一件非常头疼 ...

  7. Hive JDBC执行load时无法从本地加载数据

    通过hive-jdcv连接hive server,在应用服务端执行以下命令,报错:Hiver Server节点上找不到data.txt load data local inpath '/home/dw ...

  8. 2020-2021-1 20209307《Linux内核原理与分析》第六周作业

    这个作业属于哪个课程 <2020-2021-1Linux内核原理与分析)> 这个作业要求在哪里 <2020-2021-1Linux内核原理与分析第六周作业> 这个作业的目标 & ...

  9. [日常摸鱼]poj1151Atlantis-扫描线

    题意:给一堆长宽平行于坐标轴的长方形求并的面积 我个沙茶快写了一晚上- 大概思想就是先根据$y$坐标排个序,把$y$坐标离散化一下,放到线段树里面维护,这里的写法是让线段树的节点储存这个点对应的整段线 ...

  10. 卷积涨点论文 | Asymmetric Convolution ACNet | ICCV | 2019

    文章原创来自作者的微信公众号:[机器学习炼丹术].交流群氛围超好,我希望可以建议一个:当一个人遇到问题的时候,有这样一个平台可以快速讨论并解答,目前已经1群已经满员啦,2群欢迎你的到来哦.加入群唯一的 ...