在开发过程中,对于一系列的处理方 法,我们如果采用Action作为直接父类覆盖Execute方法直接处理的话,可能会造成Action子类过多,代码结构复杂,配置文件臃肿,代码阅读 困难等问题,因此对于同一系列的方法,我们可能采用将其放入DispatchAction的子类中去做,这样的话配置没那么麻烦,相同系列的方法放在一 起,这样解决了结构问题,可是新的问题又来了:Spring 的AOP在默认配置情况下是无法切入DispatchAction的方法的,因为DispatchAction内部的方法是通过策略设计模式实现的(根据 请求利用反射得到方法对象),为此,我想到了一种方法(在做权限管理的时候):
1、在struts-config.xml中加入下列控制器:
<controller>
<set-property property="processorClass" value="believems.hexun.com.web.action.privilege.PrivilegeInterceptor"/>
</controller>
2、believems.hexun.com.web.action.privilege.PrivilegeInterceptor实现代码如下:
public class PrivilegeInterceptor extends org.springframework.web.struts.DelegatingRequestProcessor {
@Override
protected ActionForward processActionPerform(HttpServletRequest request,
HttpServletResponse response, Action action, ActionForm form,
ActionMapping mapping) throws IOException, ServletException {
if(validatePrivilege(request, action, mapping)){//如果用户有权限,往后执行
return super.processActionPerform(request, response, action, form, mapping);
}else{
request.setAttribute("message", "你没有权限执行该操作");
request.setAttribute("urladdress", SiteUrl.readUrl("control.control.right"));
return mapping.findForward("message");
}
}
/**
* 验证用户权限
* @return
*/
private boolean validatePrivilege(HttpServletRequest request,
Action action, ActionMapping mapping) {
Method method = getCurrentMethodName(request, action, mapping);//获取当前执行的方法
//判断用户权限
//如果有权限,返回true,否则返回false
}
/**
* 获取当前执行的方法
* @return
*/
private Method getCurrentMethodName(HttpServletRequest request, Action action, ActionMapping mapping){
String methodname = "execute";
if(DispatchAction.class.isAssignableFrom(action.getClass()))//判断DispatchAction是否是所传过来的Action指向对象的父类
//如果是,则根据请求参数,取得将要执行的方法名称,并且通过反射技术取得这个方法,采用AOP切入!如果不是的话,则证明是执行的是Action的execute方法,返回execute的方法的对象。
{
methodname = request.getParameter(mapping.getParameter());//根据struts配置文件中dispatchAction的Parameter取得要执行的方法名称
}
Method method = null;
try {
method = action.getClass().getDeclaredMethod(methodname, ActionMapping.class, ActionForm.class,
HttpServletRequest.class,HttpServletResponse.class);//返回要执行的方法
} catch (Exception e) {}
return method;
}
}
利用这种方法,就可以实现spring的AOP对dispatchAction的切入了!