【Webアプリ】エラーページの設定
スポンサーリンク
こんにちは。talosです。
今回はエラーページの設定の仕方を説明します。
Webアプリを作る際は必須なので、必ず設定するようにしましょう。
解説
web.xmlを見てみます。
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> <display-name>Error_Sample</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>Faces Servlet</servlet-name> <servlet-class>javax.faces.webapp.FacesServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>/faces/*</url-pattern> </servlet-mapping> <error-page> <error-code>404</error-code> <location>/faces/404-error.xhtml</location> </error-page> <error-page> <error-code>500</error-code> <location>/faces/500-error.xhtml</location> </error-page> </web-app>
エラーページの設定をしているのはこの部分です。
<error-page> <error-code>404</error-code> <location>/faces/404-error.xhtml</location> </error-page> <error-page> <error-code>500</error-code> <location>/faces/500-error.xhtml</location> </error-page>
<error-page>タグの間に<error-code>タグと<location>タグを入れます。
<error-code>タグにはエラーページを設定したいエラーコードを書き、<location>タグにはページのパスを書きます。
JSFページの場合は/facesが付きます。
ここでは404と500だけですが、401や403、503などのよくあるエラーコードについても設定しておきましょう。
あとはそれぞれのエラーページを用意するだけです。
(ここでは404-error.xhtmlと500-error.xhtmlを用意しました)
スポンサーリンク
実行
Webアプリを立ち上げます。
立ち上がったら実際には存在しないページのURLを打ち込んでみます。
すると
自作した404エラーのページに移りました。
次にトップページに戻り、例外を起こすボタンを押してみます。
このボタンを押すとNullPointerExceptionを起こすようにしてあります。
すると
自作した500エラーのページに移りました。