类型一:自定义异常处理
<error-page>
<exception-type>com.bjsxt.drp.exceptions.AppException</exception-type>
<location>/error.jsp</location>
</error-page>
1.定义异常类AppException.java,通过super(msg);将异常信息传到父类RuntimeException中,
public class AppException extends RuntimeException {
private int errorCode;
public AppException(String msg) {
super(msg);
}
public AppException(int errorCode) {
this.errorCode = errorCode;
}
public int getErrorCode() {
return errorCode;
}
}
2.在使用的地方向上抛出异常
例如:
try {
..............
} catch (SQLException e) {
throw new AppException("删除物料失败");
} finally {
...............
}
3.根据web.xml文件配置,抛出异常com.bjsxt.drp.exceptions.AppException后转向error.jsp页面
4.在错误处理页面error.jsp中通过以下代码得到错误信息
<%=exception.getMessage()%>
(注意:错误页面开头部分要注明是错误页面:<%@ page isErrorPage="true" %> )
类型二:错误码处理
1. <!--如果错误码是404或者500则转向error.jsp页面 ,做相应处理 -->
<error-page>
<error-code>404</error-code>
<location>/http_error.jsp</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/http_error.jsp</location>
</error-page>
2.http_error.jsp
<%
//得到错误码request.getAttribute("javax.servlet.error.status_code")
Integer statusCode = (Integer)request.getAttribute("javax.servlet.error.status_code");
if (statusCode.intValue() == 404) {
response.sendRedirect(request.getContextPath() + "/404.html");
}else if (statusCode.intValue() == 500) {
response.sendRedirect(request.getContextPath() + "/500.html");
}
%>