新手用Dispatch Action
本以为通过简单的在Action中加入if else判断语句,就能够在Struts中实现不同的参数对应不同的操作,谁知道原来在Servlet能够实现的方法,却在Struts中行不通。听老师说,要通过分发Action,也就是Dispatch Action来实现。之前我开会还跟我们组的人说要用ifelse对参数进行判断呢,汗,这下算是误导他们了。下次开会的时候跟他们再细说吧。
DispatchAction其实是个非常有用的东西,可以大幅缩减Action的数量。比如说我在Struts-config.xml中建立了下面这样一个action配置:
Copy code
<action path=”/ManageUser” name=”userProfileForm” type=”com.buptsse.actions.ManageUserAction” scope=”request” validate=”true” input=”/admin/userlist.jsp” parameter=”method”>
<forward name=”userprofile” path=”/admin/userprofile.jsp”/>
<forward name=”userdel” path=”/admin/info.jsp”/>
<forward name=”useradd” path=”/admin/useradd.jsp”/>
<forward name=”userselect” path=”/admin/userselect.jsp”/>
</action>[/action]
注意其中的parameter参数,他的值是method。然后下面的是多个要转发的页面。
然后我们在ManageUserAction中:
[code]public class ManageUserAction extends DispatchAction {
public ActionForward edit(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws BusinessException {
DynaActionForm frm = (DynaActionForm) form;
try {
return mapping.findForward(”userprofile”);
}else {
return null;
}
} catch (Exception e) {
}
}
public ActionForward add(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws BusinessException {
try {
return mapping.findForward(”useradd”);
} catch (Exception e) {
}
return null;
}
public ActionForward del(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws BusinessException {
try {
return mapping.findForward(”userdel”);
} catch (Exception e) {
}
return null;
}
public ActionForward select(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws BusinessException {
try {
return mapping.findForward(”userselect”);
} catch (Exception e) {
}
return null;
}
}
注意本action一定要继承自DispatchAction。接下来我们定义了几个不同的方法,例如profile、add等,那么,我们只要在页面中按照“ /ManageUserAction.do?method=profile ”这样的格式,就能够访问这一个action中的不同的方法,从而达到用这一个action代替多个action的目的,也使得代码的维护变得非常的方便。