动用google,找到一两篇相关文章,实践成功。
建一个action基类TokenAction,使用模板方法,如下:
public ActionForward execute( ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception {
ActionForward forward = null;
if (isTokenValid(request, true)) {
forward = doExecute(mapping, form, request, response);
} else {
saveToken(request);
throw new TokenRepeatException(MessageLocator.getMessage("error.token"));
}
return forward;
}
public abstract ActionForward doExecute( ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception;
注:TokenRepeatException是自定义异常,它的父类ApplicationException在struts-config.xml中被声明,以便于action捕获。如下(我的错误消息资源是用spring来配的,没有用struts的):
<struts-config>
<global-exceptions>
<exception handler="com.chage.framework.struts.BusinessExceptionHandler" key="todo" type="com.chage.framework.exception.ApplicationException" />
</global-exceptions>
.....
</struts-config>
然后,观察这个异常处理类:
public class BusinessExceptionHandler extends ExceptionHandler {
public ActionForward execute(Exception exception,
ExceptionConfig config,
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws ServletException {
request.setAttribute("exception", exception);
if (exception instanceof TokenRepeatException) {
return mapping.findForward("tokenRepeat");
} else
//display error info in action come from
return mapping.getInputForward();
}
}
有几个注意事项,记录备案:
1.关于异常信息哪里显示: 异常显示当然不能在表单页面上了,比如说,你成功更新了一条记录后,返回list的页面,当用户回退重复提交,再返回这个list页并显示提示信息是比较合理的,最好是定义另外一个forward,我统一转向forward名称为 “tokenRepeat“,每个需要控制重复提交的action中必须定义它。最后在jsp页上加上异常显示:
<logic:present name="exception">
<font color=red> <bean:write name="exception" property="message"/></font><br>
</logic:present>
2.你必须通过action来转发而不是直接进入jsp页,因为你得调用saveToken方法来记录令牌字。