应用环境:在实际应用中,我们的业务实体类往往是通过继承一个基类,而这个基类包含了业务实体类的公共属性,比如创建者:creator,帐套:account,创建时间:createTime等等。下面,我们用struts2 interceptor来实现对公共属性的填充。
struts2 version:2.1.6 GA
1 Struts2 interceptor 实现:
-------------------------------------------------------------------------------------------------------
package com.abcdef.component.struts2;
import java.util.Map;
import com.abcdef.core.entity.PrimaryEntity;
import com.abcdef.system.entity.User;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;
@SuppressWarnings("unchecked")
public class PrimaryEntityInterceptor extends MethodFilterInterceptor {
private static final long serialVersionUID = 7224237874245817556L;
private static final String EASY_LOCK = "lock";
@Override
protected String doIntercept(ActionInvocation ai) throws Exception {
Map session = ai.getInvocationContext().getSession();
if ("login".equals(ai.getProxy().getActionName())) {
return ai.invoke();
}
User user = (User) session
.get(com.easybea.core.util.Global.SESSION_ID_KEY_IN_COOKIE);
if (user != null) {
if (ai.getAction() instanceof ModelDriven) {
ModelDriven action = (ModelDriven) ai.getAction();
if (action.getModel() instanceof PrimaryEntity) {
PrimaryEntity T = (PrimaryEntity) action.getModel();
if ("1".equals(T.getLogicLock()))
return EASY_LOCK;
if (T.getAccount() == null || "".equals(T.getAccount())) {
T.setAccount(user.getAccount());
T.setCreator(user.getUserLogin());
} else {
T.setLastUpdate(user.getUserLogin());
}
//T.setLastLoginIp(user.getLastLoginIp());
}
}
return ai.invoke();
} else {
return Action.LOGIN;
}
}
}
-------------------------------------------------------------------------------------------------------
2 在struts.xml中配置interceptor
-------------------------------------------------------------------------------------------------------
....
<interceptor name="primaryEntityInterceptor"
class="com.abcdef.component.struts2.PrimaryEntityInterceptor" />
....
<interceptor-stack name="easybeaStack">
<interceptor-ref name="paramsPrepareParamsStack" />
<interceptor-ref name="defaultStack" />
<interceptor-ref name="primaryEntityInterceptor">
<param name="includeMethods">save</param>
<param name="excludeMethods">
input,list,lock,unlock
</param>
</interceptor-ref>
</interceptor-stack>
-------------------------------------------------------------------------------------------------------
3 一定不要忘记实现 <interceptor-ref name="paramsPrepareParamsStack" />,否则不能工作。