在Strtuts2中使用异常拦截器,对各种异常进行自定义处理,对用户提供更友好的信息而不是JSP的默认异常信息。步骤如下:
1)『Struts.xml』的定义
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="JProject" extends="struts-default">
<interceptors>
<interceptor name="bizException" class="com.kalphix.env.ExceptionMappingInterceptor"/>
</interceptors>
<default-interceptor-ref name="bizException"></default-interceptor-ref>
<global-results>
<result name="allexception" >/pages/envpages/allexception.jsp</result>
<result name="bizexception" >/pages/envpages/bizexception.jsp</result>
<result name="error">/pages/envpages/error.jsp</result>
</global-results>
<action name="login" class="com.kalphix.web.Login" method="login">
<result name="success">/pages/loged.jsp</result>
</action>
</package>
</struts>
2)异常拦截器的实装。
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.interceptor.StaticParametersInterceptor;
public class ExceptionMappingInterceptor extends StaticParametersInterceptor {
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
public String intercept(ActionInvocation invocation) throws Exception {
System.out.println("ExceptionMappingInterceptor#intercept");
try {
return invocation.invoke();
} catch (Exception e) {
ActionSupport actionSupport = (ActionSupport) invocation
.getAction();
exception(e, actionSupport);
return "bizexception";//Action.ERROR;
}
}
private void exception(Exception e, ActionSupport actionSupport)
throws Exception {
System.out.println("ExceptionMappingInterceptor#exception");
if (e instanceof BizException) {
BizException be = (BizException) e;
// String who = actionSupport.getText(be.getWho());
// String errorType = actionSupport.getText(
// be.getErrorType(),
// new String[] { who, be.getValue() });
String error = be.getMessage();
actionSupport.addActionError(error);
} else {
actionSupport.addActionError("Exception");
// throw e;
}
}
}