Spring通过配置文件实现响应异常拦截,并跳转到错误信息提示页面

我们项目中由于客户端的一些操作导致响应出现错误,比如说404,500等,为了达到一个友好的提示效果,出现错误将页面跳转到我们制定的错误处理页面,我们可以通过配置web.xml文件来达到这样的一个效果,下面是我完成这个功能的流程以及代码部分:

1.首先是配置web.xml这个文件添加上我们的错误捕获代码,可以参考下面的代码,配置上自己需要捕获的错误类型,比如404,400,500都可以用这种方式添加上,error-code中就写错误类型,location 中就写上要跳转的指定页面:

<!-- 用来判断状态码,跳转到相应页面 -->
  <error-page>
  	<error-code>404</error-code>
  	<location>/toexp</location>
  </error-page>
  <error-page>
  	<error-code>400</error-code>
  	<location>/toexp</location>
  </error-page>
  <error-page>
  	<error-code>500</error-code>
  	<location>/toexp</location>
  </error-page>

2.在这里跳转我是先跳到controller层然后再跳转至相应的页面,这里大家可以参考一下:

//用于跳转到错误处理页面
	@RequestMapping("toexp")
	public String toexp(){
		return "expected";
	}

3.最后就是跳转到我们要显示给客户端看的错误提示页面就可以了,遇到错误的话,最终展示给客户端的就是这个指定的页面了:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>异常页面</title>
		<link href="/css/bootstrap.min.css" rel="stylesheet">
		<script type="text/javascript" src="/js/jquery-3.0.0.min.js"></script>
	</head>

	<body>
		<nav class="navbar navbar-inverse">
		<div class="container-fluid">
			<div class="navbar-header">
				<a class="navbar-brand" href="#">管理系统</a>
			</div>
		</div>
		</nav>
		<div class="container-fluid">
			<h1>异常跳转显示页面</h1>
		</div>
	</body>

</html>

4.简单的页面展示效果:

Spring通过配置文件实现响应异常拦截,并跳转到错误信息提示页面