例外時のフォワード処理

昨日の日記の例外(NoRoleException含む)発生時の処理で、StrutsのExceptionHandlerを使ってそこそこうまく解決したので公開。

ExceptionForwardHandler.java

public class ExceptionForwardHandler extends ExceptionHandler {
  @Override
  public ActionForward execute(Exception ex, 
      ExceptionConfig ae, 
      ActionMapping mapping, 
      ActionForm formInstance,
      HttpServletRequest request, 
      HttpServletResponse response) throws ServletException {
    super.execute(ex, ae, mapping, formInstance, request, response);
    return (ae.getPath() != null ? ((S2ActionMapping) mapping).createForward(ae.getPath()) : mapping.getInputForward());
  }
}

struts-config.xml

<global-exceptions>
  <exception key="errors.norole"
    type="org.seasar.struts.exception.NoRoleRuntimeException"
    path="/index.jsp"
    handler="ExceptionForwardHandler"
  />
</global-exceptions>

でNoRoleExceptionが発生したときに/WEB-INF/jsp/index.jspに遷移してエラーメッセージを表示してくれる。
こうしてみるとStrutsの基本構成ってやっぱうまくできてるなーと感心する。