以前开发的时候,一直没错处理错误页面的问题,如果tomcat报错,就直接把错误的信息打印出来,找不到地址的时候就直接给出一个404错误,因为做的项目一直是没有上线的,所以,一直没有留意过这个问题,所以今天要记录一下错误的页面的指定。
error-page元素就是用来克服这些问题的。
//放置于web.xml末尾处
<error-page>
</error-page>
它有两个可能的子元素,分别是:
<error-code>
//错误码
</error-code>
<location>
//指出在给定的HTTP错误代码出现时使用的URL
</location>
和
<exception-type>
//Java异常
</exception-type>
<location>
//指出在给定的HTTP错误代码出现时使用的URL
</location>
下面给出使用事例
http://www.plinko.net/404/ (全球错误页面)
元素一使用实例:
<error-page>
<error-code>404</error-code>
<location>/NotFound.jsp</location>
</error-page>
元素二使用实例:
<error-page>
<exception-type>packageName.className</exception-type>
<location>/SomeURL</location>
</error-page>
————–2017年4月更新—————-
如果要自己通过控制器进行控制可以在location里面填入自己的控制器的地址,然后在控制器里面通过request.getAttributeNames()获取相关信息
如下实例:
web.xml
<error-page>
<error-code>400</error-code>
<location>/error/handle</location>
</error-page>
controller
@Controller
@RequestMapping("/error")
public class ErrorController extends BaseController {
@RequestMapping("/handle")
public ResponseEntity<Map<String, Object>> handle(HttpServletRequest request) {
Enumeration<String> attributeNames = request.getAttributeNames();
while (attributeNames.hasMoreElements()) {
String attributeName = attributeNames.nextElement();
Object attribute = request.getAttribute(attributeName);
System.out.println("request.attribute['" + attributeName + "'] = " + attribute);
}
return null;
}
}