使用场景:
如果action针对每次请求都要执行一些相同的业务逻辑, 那么可以实现Preparable接口,将预处理业务逻辑写在prepare()方法里
Preparable 接口定义:
public interface Preparable { void prepare() throws Exception;}
prepare何时被执行:
prepare方法由PrepareInterceptor拦截器调用执行 com.opensymphony.xwork2.interceptor.PrepareInterceptor public String doIntercept(ActionInvocation invocation) throws Exception { Object action = invocation.getAction();if (action instanceof Preparable) {
try { String[] prefixes; if (firstCallPrepareDo) { prefixes = new String[] {ALT_PREPARE_PREFIX, PREPARE_PREFIX}; } else { prefixes = new String[] {PREPARE_PREFIX, ALT_PREPARE_PREFIX}; } PrefixMethodInvocationUtil.invokePrefixMethod(invocation, prefixes); } catch (InvocationTargetException e) { // just in case there's an exception while doing reflection, // we still want prepare() to be able to get called. LOG.warn("an exception occured while trying to execute prefixed method", e); } catch (IllegalAccessException e) { // just in case there's an exception while doing reflection, // we still want prepare() to be able to get called. LOG.warn("an exception occured while trying to execute prefixed method", e); } catch (Exception e) { // just in case there's an exception while doing reflection, // we still want prepare() to be able to get called. LOG.warn("an exception occured while trying to execute prefixed method", e); }// 必须执行或初始化的一些业务操作 action prepare()方法 if (alwaysInvokePrepare) { ((Preparable) action).prepare(); }
}return invocation.invoke();
}
使用方法:
使用basicStack拦截器栈
<action name="list" class="org.apache.struts2.showcase.action.SkillAction" method="list"> <result>/empmanager/listSkills.jsp</result> <interceptor-ref name="basicStack" /> <!-- 使用basicStack拦截器栈, 该拦截器栈在 struts-default.xml 已配置, 包括了prepare --></action>(注: struts-default.xml 里定义的 basicStack拦截器栈
<!-- Basic stack -->
<interceptor-stack name="basicStack"> <interceptor-ref name="exception"/> <interceptor-ref name="servletConfig"/> <interceptor-ref name="prepare"/> <interceptor-ref name="checkbox"/> <interceptor-ref name="multiselect"/> <interceptor-ref name="actionMappingParams"/> <interceptor-ref name="params"> <param name="excludeParams">dojo\..*,^struts\..*</param> </interceptor-ref> <interceptor-ref name="conversionError"/> </interceptor-stack>)
或者直接指定prepare拦截器
<action name="list" class="org.apache.struts2.showcase.action.SkillAction" method="list"> <result>/empmanager/listSkills.jsp</result> <interceptor-ref name="prepare" /> <!-- 直接指定prepare拦截器 --></action>