异常处理

1、web.xml
  i.error-code:错误码 
  <error-page>  
      <error-code>404</error-code> 
      <location>/404.jsp</location>
  </error-page>
  
  ii.exception-type
当servlet执行时,可能产生许多异常。而当异常产生时,Web容器将产生一个包含A Servlet Has Occurred消息的缺省页。但是,用户也可返回一个容器,该容器应包含为给定异常指定的错误页。
  <error-page>  
      <exception-type>org.sprngside.bookstore.UserNotFound</exception-type>  
      <location>/userNotFound.jsp</location>
  </error-page>
  
  
2、jsp
 <@ errorPage="error.jsp">


3、Spring MVC里的异常控制
   spring-mvc可在xxx-serverlet.xml里定义default和 按Excepiton类型影射的错误页面,
   和Servlet规范比,主要作了Spring特色的JSP路径转向和日志记录.参见bookstore-servlet.xml
  
 <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
      <property name="defaultErrorView" value="/error.jsp"/>
      <property name="exceptionMappings">
           <props>               
                <prop key="org.springside.framework.base.BusinessException">/businessError.jsp</prop>
            </props>       
       </property>   
 </bean>

 

=========================================
  error.jsp会同时处理jsp,servlet,和spring抛过来的异常
  
  jsp的异常在exception 变量中.(要指定<%@ page isErrorPage="true" %>)
  
  spring的异常在(Exception) request.getAttribute("exception")
  
  servlet的异常在(Exception)request.getAttribute("javax.servlet.error.exception")
  
  使用 (String) request.getAttribute("javax.servlet.error.request_uri")获得 request_uri
  使用 logger.error(exception.getMessage(), exception); 记录整个异常栈

   
  · javax.servlet.error.exception:实际的异常掷出的Throwable对象
  · javax.servlet.error.request_uri:导致问题产生的资源的URI字符串对象
  · javax.servlet.error.status_code:错误类型的整形值
  · javax.servlet.error.exception_type:产生错误的异常类的实例
  · javax.servlet.error.message:异常信息字符串
  
  


error.jsp 完整的代码

<%@ page contentType="text/html;charset=UTF-8" isErrorPage="true" %>
<%@ page import="org.apache.commons.logging.LogFactory" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Error Page</title>
    <script src="<c:url value="/scripts/prototype.js"/>" type="text/javascript"></script>
    <script language="javascript">
        function showDetail()
        {
            $('detail_error_msg').toggle();
        }
    </script>
</head>

<body>

<div id="content">
    <%
        //Exception from JSP didn't log yet ,should log it here.
        String requestUri = (String) request.getAttribute("javax.servlet.error.request_uri");
        LogFactory.getLog(requestUri).error(exception.getMessage(), exception);
    %>

    <h3>System Runtime Error: <br><%=exception.getMessage()%></h3><br>

    <button onclick="history.back();">Back</button><br>

    <p><a href="#" onclick="showDetail();">Administrator click here to get the detail.</a></p>

    <div id="detail_error_msg" style="display:none">
        <pre><%exception.printStackTrace(new java.io.PrintWriter(out));%></pre>
    </div>
</div>
</body>
</html>