2011-08-15 248 views
110

我使用<error-page>元素web.xml中指定友好的錯誤頁面,當用戶遇到一定的誤差,如用404代碼錯誤: 如何在web.xml中指定默認錯誤頁面?

<error-page> 
     <error-code>404</error-code> 
     <location>/Error404.html</location> 
</error-page> 

但是,我想,如果用戶確實不符合<error-page>中指定的任何錯誤代碼,他或她應該看到一個默認的錯誤頁面。我如何使用web.xml中的元素來做到這一點?

+2

你在使用/目標servletcontainer什麼的servlet版本你的'web.xml'聲明?自從Servlet 3.0以來,只有一種簡單的方法。 – BalusC

+0

我正在使用Tomcat 6,servlet 2.5 – ipkiss

回答

201

上的Servlet 3.0或更新版本,你可以只指定

<web-app ...> 
    <error-page> 
     <location>/general-error.html</location> 
    </error-page> 
</web-app> 

但正如你還在Servlet 2.5的,有沒有其他辦法比單獨指定每一個常見的HTTP錯誤。您需要確定最終用戶可能面對的HTTP錯誤。在準系統Web應用程序中,例如使用HTTP身份驗證,具有禁用的目錄列表,使用自定義servlet和可能會拋出未處理異常的代碼,或者沒有實現所有方法,則您希望將其設置爲HTTP錯誤401 ,403,500和503。

<error-page> 
    <!-- Missing login --> 
    <error-code>401</error-code> 
    <location>/general-error.html</location> 
</error-page> 
<error-page> 
    <!-- Forbidden directory listing --> 
    <error-code>403</error-code> 
    <location>/general-error.html</location> 
</error-page> 
<error-page> 
    <!-- Missing resource --> 
    <error-code>404</error-code> 
    <location>/Error404.html</location> 
</error-page> 
<error-page> 
    <!-- Uncaught exception --> 
    <error-code>500</error-code> 
    <location>/general-error.html</location> 
</error-page> 
<error-page> 
    <!-- Unsupported servlet method --> 
    <error-code>503</error-code> 
    <location>/general-error.html</location> 
</error-page> 

這應該涵蓋最常見的。

+0

您能指定一個通用錯誤頁面,然後用''標籤覆蓋某些錯誤代碼嗎? – Qix

+6

@Tomas:Tomcat傢伙和你有同樣的問題。這在規範中沒有任何字面提及,只有規範中的圖14-10和'web.xml' XSD文件證明''和''變成了可選項而不是必需的。參見[問題52135](https://issues.apache.org/bugzilla/show_bug.cgi?id=52135)。 – BalusC

+0

http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd沒有爲元素指定子項,因此將上述代碼粘貼到Servlet 2.5 web.xml中會導致XSD驗證錯誤。如果我評論他們,但它工作正常,謝謝! –

15

你也可以做這樣的事情:

<error-page> 
    <error-code>403</error-code> 
    <location>/403.html</location> 
</error-page> 

<error-page> 
    <location>/error.html</location> 
</error-page> 

錯誤代碼403它將返回頁面403.html,以及任何其他的錯誤代碼,將返回的error.html頁。

0

您還可以指定<error-page>使用<exception-type>例外,例如下面:

<error-page> 
    <exception-type>java.lang.Exception</exception-type> 
    <location>/errorpages/exception.html</location> 
</error-page> 

或MAP使用<error-code>一個錯誤代碼:

<error-page> 
    <error-code>404</error-code> 
    <location>/errorpages/404error.html</location> 
</error-page> 
+0

我看不到任何投票原因。 –

相關問題