關於JSP異常的處理

來源:互聯網
上載者:User

標籤:style   blog   http   io   color   ar   使用   java   sp   

jsp中錯誤處理頁面-isErrorPage="true"

舉例說明:mustBeError.jsp

1 <%@ page contentType="text/html; charset=gb2312" 2 language="java" import="java.sql.*,javax.servlet.*,javax.servlet.http.*" errorPage="error.jsp" %>3 <%4   //這個頁面一定會出錯。5   int i=0;6   int j=1;7   out.println(j/i);8 %>

在此中通過errorPage="error.jsp"來指定出錯時錯誤處理頁面

error.jsp

 1  <%@ page contentType="text/html; charset=gb2312" language="java" isErrorPage="true" import="java.io.*"%> 2  <html> 3  <head> 4    <title>出錯了!</title> 5    <meta http-equiv="Content-Type" content="text/html; charset=gb2312"> 6  </head> 7  <body> 8    出錯了!<br> 9    發生了以下的錯誤:10    <br><hr>11  <font color=red><hr>12    getMessage():<br>13    <%=exception.getMessage()%><br><hr>14    getLocalizedMessage():<br>15    <%=exception.getLocalizedMessage()%><br><hr>16    PrintStatckTrace():<br>17    <%18    StringWriter sw=new StringWriter();19    PrintWriter pw=new PrintWriter(sw);20    exception.printStackTrace(pw);21    out.println(sw);22    %><br>23   </font>24  </body> 

在web.xml中聲明異常和錯誤頁面

 1 例如: 2 <?xml version="1.0" encoding="ISO-8859-1"?> 3  4 <web-app xmlns="http://java.sun.com/xml/ns/j2ee" 5 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 6 xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee web-app_2_4.xsd" 7 version="2.4"> 8 <error-page> 9 <error-code>404</error-code>10 <location>/pageNotFound.html</location>11 </error-page>12 13 <error-page>14 <exception-type>java.lang.NumberFormatException</exception-type>15 <location>/NumberFormatException.html</location>16 </error-page> 17 18 </web-app> 

說明:指定錯誤碼為404是,調用/pageNotFound.html
也可以指定錯誤類型如:java.lang.NumberFormatException,出現此錯誤類型是調用/NumberFormatException.html

 

在error.jsp中,首先在page指令中指定:

isErrorPage="true"

這是非常關鍵的地方,只有這樣指定,這個頁面才能進行錯誤處理,才能使用exception對象。

exception對象有幾個非常重要的方法,用於獲得出錯的資訊,這些方法如下:

 

? <%=exception.getMessage()%>
? <%=exception.getLocalizedMessage()%>
? <% exception.printStackTrace(PrintWriter);%>

最後一個方法用於列印錯誤堆棧。如果需要在錯誤頁面以外使用這個exception對象,那麼可以這樣把exception對象儲存起來:

session.setAttribute("myError",exception);

在另一個頁面使用:

Exception exception=( Exception )session.getAttribute("myError");

把這個異常對象引入進來。

關於JSP異常的處理

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.