Strutsの例外処理についてまとめます。Strutsの例外処理はいわゆる宣言型の記述が可能になっています。 全てのアクション、もしくは特定のアクションで××Exceptionが発生した場合はこのエラー画面へ遷移、などということができます。また、ある例外が発生したときに画面遷移だけでなく特殊な処理をしたい場合、例外ハンドラを定義することによって処理を組み込むこともできます。たとえばある例外で、内部のエラーIDを見て遷移先を切り替えたい、なんてことが可能です。
サンプルで見てみます。アクションクラスで特定の例外(NormalException?としました)が発生したときに、error.jspに遷移させることを考えます。
normalEx -> エラー発生 -> error.jsp
という流れのサンプルです。
<global-exceptions> <exception key="errors.NormalException" type="nu.mine.kino.strutsexamples.exceptions.NormalException" path="/WEB-INF/jsp/error.jsp"/> <!-- このkey値でActionMessageを生成してスコープにセットしている。 メッセージのvalueは、propertiesから取得している。 --> </global-exceptions>
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { エラーを入れるか throw new NormalException("普通のハンドリングをする例外!"); }
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <%@ page language="java" contentType="text/html; charset=UTF-8" %> <%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %> <%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %> <%@ taglib uri="http://struts.apache.org/tags-logic" prefix="logic" %> <html:html xhtml="true" lang="true"> <head> <title>エラーハンドラのサンプル</title> <meta http-equiv="Content-Type" content="application/xhtml+xml; charset=UTF-8" /> <html:base /> </head> <body> <ul> <html:messages id="message"> <li><bean:write name="message" /></li> </html:messages> </ul> <hr /> <html:errors /> </body> </html:html>
この記事は
現在のアクセス:46884