在web.xml配置404和500错误及异常
Web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!-- 配置错误处理 -->
<error-page>
<error-code>404</error-code>
<location>/404.html</location>
</error-page>
<error-page>
<error-code>505</error-code>
<location>/505.html</location>
</error-page>
<!-- 配置异常处理 -->
<error-page>
<exception-type>javax.servle.ServletException</exception-type>
<location>/error.html</location>
</error-page>
<error-page>
<exception-type>java.lang.NullPointerException</exception-type>
<location>/error.html</location>
</error-page>
</web-app>
JSP页面的关键在于:
1、isErrorPage="true"
2、response.setStatus(HttpServletResponse.SC_OK);
<%@ page language="java" contentType="text/html; charset=GBK" isErrorPage="true" pageEncoding="GBK"%>
<%response.setStatus(HttpServletResponse.SC_OK);%>