资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

怎么在Springboot中自定义错误页面-创新互联

这篇文章给大家介绍怎么在Springboot中自定义错误页面,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

成都创新互联公司为客户提供专业的成都网站设计、成都网站制作、外贸网站建设、程序、域名、空间一条龙服务,提供基于WEB的系统开发. 服务项目涵盖了网页设计、网站程序开发、WEB系统开发、微信二次开发、成都做手机网站等网站方面业务。

默认效果示例


springboot他是有自己默认的处理机制的。在你刚创建一个springboot项目去访问一个没有的路径会发现他是会弹出来这样的信息。

怎么在Springboot中自定义错误页面

而我们用postman直接接口访问,会发现他返回的不再是页面。默认响应一个json数据

怎么在Springboot中自定义错误页面

这时候该有人在想,springboot他是如何识别我们是否是页面访问的呢?

效果示例原因

springboot默认错误处理机制他是根据Headers当中的Accept来判断的,这个参数无论是postman访问还是页面访问都会传入。

页面访问的时候他传入的是test/html

怎么在Springboot中自定义错误页面

而postman是这个

怎么在Springboot中自定义错误页面

错误机制原理

原因我们大概了解了,接下来通过翻看源码我们简单的来理解一下他的原理。

简单回顾springboot原理

springboot之所以开箱即用,是因为很多框架他已经帮我们配置好了,他内部有很多AutoConfiguration,其中ErrorMvcAutoConfiguration类就是错误机制配置。

存放于这个jar包下

怎么在Springboot中自定义错误页面

springboo 2.4版本当中ErrorMvcAutoConfiguration存放于这个路径

怎么在Springboot中自定义错误页面

springboot 1.5版本ErrorMvcAutoConfiguration存放于这个路径

怎么在Springboot中自定义错误页面

当然他只是版本之间类存放位置发生一些改动,但是源码区别不是很大。

springboot内部使用到配置的地方,都是去容器当中取的,容器的作用就是将这些配置实例化过程放到了启动,我们在用的时候直接从容器当中取而无需创建,这也就是围绕容器开发的原因,在使用springboot的时候应该也都会发现,我们想要修改springboot的一些默认配置都会想方设法把他放到容器当中,他才会生效。

在源码当中会发现存在大量@ConditionalOnMissingBean,这个就是假如我们项目当中配置了该项配置,springboot就不会使用他的默认配置了,就直接用我们配置好的。

ErrorMvcAutoConfiguration配置

ErrorMvcAutoConfiguration给容器中添加了以下组件:

1、DefaultErrorAttributes

怎么在Springboot中自定义错误页面

页面当中错误信息,以及访问时间等等,都是在DefaultErrorAttributes当中的这两个方法当中获取的。

@Override
	public Map getErrorAttributes(WebRequest webRequest, ErrorAttributeOptions options) {
		Map errorAttributes = getErrorAttributes(webRequest, options.isIncluded(Include.STACK_TRACE));
		if (Boolean.TRUE.equals(this.includeException)) {
			options = options.including(Include.EXCEPTION);
		}
		if (!options.isIncluded(Include.EXCEPTION)) {
			errorAttributes.remove("exception");
		}
		if (!options.isIncluded(Include.STACK_TRACE)) {
			errorAttributes.remove("trace");
		}
		if (!options.isIncluded(Include.MESSAGE) && errorAttributes.get("message") != null) {
			errorAttributes.put("message", "");
		}
		if (!options.isIncluded(Include.BINDING_ERRORS)) {
			errorAttributes.remove("errors");
		}
		return errorAttributes;
	}

	@Override
	@Deprecated
	public Map getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) {
		Map errorAttributes = new LinkedHashMap<>();
		errorAttributes.put("timestamp", new Date());
		addStatus(errorAttributes, webRequest);
		addErrorDetails(errorAttributes, webRequest, includeStackTrace);
		addPath(errorAttributes, webRequest);
		return errorAttributes;
	}
2、BasicErrorController

处理默认/error请求

怎么在Springboot中自定义错误页面

也正是BasicErrorController这两个方法,来判断是返回错误页面还是返回json数据

@RequestMapping(produces = MediaType.TEXT_HTML_VALUE)
	public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
		HttpStatus status = getStatus(request);
		Map model = Collections
				.unmodifiableMap(getErrorAttributes(request, getErrorAttributeOptions(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> error(HttpServletRequest request) {
		HttpStatus status = getStatus(request);
		if (status == HttpStatus.NO_CONTENT) {
			return new ResponseEntity<>(status);
		}
		Map body = getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.ALL));
		return new ResponseEntity<>(body, status);
	}
3、ErrorPageCustomizer

怎么在Springboot中自定义错误页面

系统出现错误以后来到error请求进行处理;(就相当于是web.xml注册的错误页 面规则)

怎么在Springboot中自定义错误页面

加粗样式

4、DefaultErrorViewResolver

DefaultErrorViewResolverConfiguration内部类

在这里我们可以看出他将DefaultErrorViewResolver注入到了容器当中

怎么在Springboot中自定义错误页面

DefaultErrorViewResolver这个对象当中有两个方法,来完成了根据状态跳转页面。

@Override
	public ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status,
			Map model) {
			
		//获取错误状态码,这里可以看出他将状态码传入了resolve方法
		ModelAndView modelAndView = resolve(String.valueOf(status), model);
		if (modelAndView == null && SERIES_VIEWS.containsKey(status.series())) {
			modelAndView = resolve(SERIES_VIEWS.get(status.series()), model);
		}
		return modelAndView;
	}

	private ModelAndView resolve(String viewName, Map model) {
		//从这里可以得知,当我们报404错误的时候,他会去error文件夹找404的页面,如果500就找500的页面。
		String errorViewName = "error/" + viewName;
		//模板引擎可以解析这个页面地址就用模板引擎解析
		TemplateAvailabilityProvider provider = this.templateAvailabilityProviders
				.getProvider(errorViewName, this.applicationContext);
		//模板引擎可用的情况下返回到errorViewName指定的视图地址
		if (provider != null) {
			return new ModelAndView(errorViewName, model);
		}
		//模板引擎不可用,就在静态资源文件夹下找errorViewName对应的页面 error/404.html
		return resolveResource(errorViewName, model);
	}

组件执行步骤

一但系统出现4xx或者5xx之类的错误;ErrorPageCustomizer就会生效(定制错误的响应规则);就会来到/error 请求;就会被BasicErrorController处理;去哪个页面是由DefaultErrorViewResolver解析得到的;

代码示例

这里我选择直接上代码,方便大家更快的上手。

1、导入依赖

这里我引用了thymeleaf模板,springboot内部为我们配置好了页面跳转功能。

这是本人写的一篇关于thymeleaf的博客,没用过的或者不是很了解的可以学习一下!

thymeleaf学习: https://blog.csdn.net/weixin_43888891/article/details/111350061.


	
		org.springframework.boot
		spring-boot-starter-thymeleaf
	
	
		org.springframework.boot
		spring-boot-starter-web
	

	
		org.springframework.boot
		spring-boot-starter-tomcat
		provided
	
2、自定义异常

作用:面对一些因为没找到数据而报空指针的错误,我们可以采取手动抛异常。

package com.gzl.cn;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;

@ResponseStatus(HttpStatus.NOT_FOUND)
public class NotFoundException extends RuntimeException {

  public NotFoundException() {
  }

  public NotFoundException(String message) {
    super(message);
  }

  public NotFoundException(String message, Throwable cause) {
    super(message, cause);
  }
}
3、定义异常拦截
package com.gzl.cn.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice
public class ControllerExceptionHandler {

  private final Logger logger = LoggerFactory.getLogger(this.getClass());


  @ExceptionHandler(Exception.class)
  public ModelAndView exceptionHander(HttpServletRequest request, Exception e) throws Exception {
    logger.error("Requst URL : {},Exception : {}", request.getRequestURL(),e);
		
		//假如是自定义的异常,就让他进入404,其他的一概都进入error页面
    if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null) {
      throw e;
    }

    ModelAndView mv = new ModelAndView();
    mv.addObject("url",request.getRequestURL());
    mv.addObject("exception", e);
    mv.setViewName("error/error");
    return mv;
  }
}
4、创建测试接口
package com.gzl.cn.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import com.gzl.cn.NotFoundException;

@Controller
public class HelloController {

  //这个请求我们抛出我们定义的错误,然后被拦截到直接跳到404,这个一般当有一些数据查不到的时候手动抛出
  @GetMapping("/test")
  public String test(Model model){
    String a = null;
    if(a == null) {
    	throw new NotFoundException();
    }
    System.out.println(a.toString());
    return "success";
  }
  
  //这个请求由于a为null直接进500页面
  @GetMapping("/test2")
  public String test2(Model model){
    String a = null;
    System.out.println(a.toString());
    return "success";
  }
}
5、创建404页面




Insert title here


	

404

  

对不起,你访问的资源不存在

6、创建error页面




Insert title here


	

错误

  

对不起,服务异常,请联系管理员

     
  
  
  
            
7、项目结构

怎么在Springboot中自定义错误页面

8、运行效果

http://localhost:8080/test2

这时候可以观察到,那段代码在此处生效了,这样做的好处就是客户看不到,看到了反而也不美观,所以采取这种方式。

怎么在Springboot中自定义错误页面

访问一个不存在的页面

怎么在Springboot中自定义错误页面

访问http://localhost:8080/test
这个时候会发现他跳到了404页面

怎么在Springboot中自定义错误页面

关于怎么在Springboot中自定义错误页面就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。


当前题目:怎么在Springboot中自定义错误页面-创新互联
当前URL:http://cdkjz.cn/article/ijghj.html
返回首页 了解更多建站资讯
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

业务热线:400-028-6601 / 大客户专线   成都:13518219792   座机:028-86922220