struts2 Preparable接口

本文详细介绍了在Struts2框架中如何通过实现Preparable接口并在prepare方法中编写预处理业务逻辑,以及如何在不同场景下正确使用基本栈拦截器栈和直接指定prepare拦截器来优化请求处理流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用场景:
如果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>


原文:http://www.cnblogs.com/mount/archive/2011/11/08/2241046.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值