Struts里这两个玩意还是十分有用的,近来学习到,故总结之
首先,
DispatchAction
的作用简单地说就是把原来我们写在多个
acton
里的操作放在同一个
action里处理,比如在商品购物系统中,有增加商品,删除商品,修改商品和查看商品,以前的话,要写三个action来操作之,现在可以合在一个action里进行操作了,可以创建一个类,继承自dispatchaction类的子类,不需要覆盖execute()方法。比如
import org.apache.struts.actions.DispatchAction;
public class ItemeAction extends DispatchAction{
//增加商品
public ActionForward add(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
...
...
}
/**编辑商品**/
public ActionForward edit(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
...
...
}
}
接着,我们配置
<action path="/item"
input="inputitem.jsp"
parameter="method" scope="request"
type="ItemeAction"
validate="false">
</action>
上面的配置,要注意的是,要加上parameter="method".当itemaction这个类执行时,它实际上执行的是基类的dispatchaction的execute方法。DispatchAction根据参数method的值来确定具体调用的是其中的哪一个方法,比如一个用户的调用是
http://localhost/xxx/item?method=add,则调用itemaction类add的方法
再来看下lookupdispatchaction.该类是DispatchAction类的一个子类,它的应用场合在于多个同名提交按钮的表单场合。比如在一个购物的应用中,一个按钮用来“更新”购物车,一个用来移除购物车里的商品,一个用来做“提交结帐”的功能,假如他们的名字都叫action的按钮,则代码为
<html:form action="/cart">
<html:submit property="action">
<bean:message key="cart.update"/> </html:submit>
<html:submit property="action">
<bean:message key="cart.check"/>
</html:submit>
.............. </html:form>
然后配置其action,
<action path="/carts"
type="cartaction"
name="cartForm"
scope="request"
parameter="action">
//注意这里parameter名要为action
</action>,
接下来是创建lookupdispatchaction类的子类,扩展LookupDispatchAction类,需要实现getKeyMethodMap()方法,该方法返回java.util.Map类的对象,如
protected Map getKeyMethodMap() {标签:LookupDispathAction,request,mapping,DispatchAction,public,add,VS,action,structs From: https://blog.51cto.com/u_14230175/5911331
Map map = new HashMap();
map.put("cart.update", "update");
map.put("cart.check", "checkcart");
return map;
}
public ActionForward update(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
// do add
return mapping.findForward("success");
}
public ActionForward checkcart(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
// do delete
return mapping.findForward("success");
}