Servlet異常處理

Servlet異常處理
1. 聲明異常處理
聲明兩種錯誤處理:HTTP錯誤代碼的處理 和 指定程序中產生的java異常的處理。
在web.xml文件中聲明對各種異常的處理方法。
元素結構:
<error-page>
|____<error-code> or <exception-type>
|
|____<location>

<error-code>: 制定錯誤代碼。
<exception-type>: 制定java異常類的完整限定名。
<location>: 給出用於響應HTTP錯誤代碼或者Java異常的資源的路徑。

HTTP異常的處理
利用web.xml靜態設置錯誤響應
[code]<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2eehttp://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">

<display-name>Test My Servlet</display-name>
<description>
Test My Servlet
</description>

<error-page>
<error-code>404</error-code>
<location>/myjsp/error.html</location>
</error-page>
</web-app>[/code]我測試發現不行!

我們也可以將error.html改爲一個Servlet類來處理。
Servlet容器在請求對象中設置的屬性
屬性名字 屬性類型 屬性說明
[code]javax.servlet.error.status_code:  Integer HTTP協議的狀態代碼
javax.servlet.error.exception_type: Class 未捕獲異常的Class類的對象
javax.servlet.error.message: String 傳遞給sendError()方法的消息
javax.servlet.error.exception: Throwable 調用錯誤頁面的未捕獲異常
javax.servlet.error.request_uri: String 當前請求的URI
javax.servlet.error.servlet_name: String 導致錯誤頁面被調用的Servlet的名字[/code]


java程序中產生的異常處理
將上面web.xml的<error-code>改爲<exception-type>後,輸入類似:
<exception-type>java.io.FileNotFoundException</exception-type>
當文件找不到時捕獲這個異常並通過<location>去調用處理。


最後,HttpServletResponse裏面有HTTP協議所定義的web響應數字。
利用ServletRequest 的getRequestDispatcher()得到getRequestDispatcher對象,
調用forward()方法去調用另一個Servlet類。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章