转载请申明作者。
如果大家用过DispatchAction的话,接触MappingDispatchAction的话就不是很难了,大家记住了这是struts1.2里新加入的。
首先说一下它的的优点:
(1)可以为每个响应用户请求的Action方法定义自己的name,validate,input和scope等参数,而在使用DispatchAction时,这些参数都是被Action中的所有方法所共享的。
(2) 在使用DispatchAction时,所执行的Action方法在url中是能显示出来的,也就是用户可以通过地址栏或者提交的数据得到所执行的方法。这有安全隐患。而MappingDispatchAction则避免了用户知道响应用户请求的Action方法的名称。
这是最简单的例子,若感觉有必要回在追加的 废话少说,开始写例子:
1。先从Action下手吧,Action要继承MappingDispatchAction,不要重写execute方法,说白了就是不要出现execute方法。
public class MovementAction extends MappingDispatchAction {
//省略了页面转发,直接在控制台输出
public ActionForward eat(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
System.out.println("eat");
return null;
}
public ActionForward drink(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
System.out.println("drink");
return null;
}
public ActionForward play(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
System.out.println("play");
return null;
}
public ActionForward happy(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
System.out.println("happy");
return null;
}
}
2。配置struts-config.xml:
<action-mappings >
<action path="/eat" type="com.yourcompany.struts.action.MovementAction" parameter="eat" />
<action path="/drink" type="com.yourcompany.struts.action.MovementAction" parameter="drink" />
<action path="/play" type="com.yourcompany.struts.action.MovementAction" parameter="play" />
<action path="/happy" type="com.yourcompany.struts.action.MovementAction" parameter="happy" />
</action-mappings>
3。编写MyJsp.jsp:
<a href="/abc/eat.do?method=eat">吃</a>
<a href="/abc/drink.do?method=drink">喝</a>
<a href="/abc/play.do?method=play">玩</a>
<a href="/abc/happy.do?method=happy">乐</a>
这里与DispatchAction不同的是在struts-config.xml里<action>中的parameter参数的值不是统一的,
值跟Action中的方法名字是对应的,比如parameter="eat" 则在MovementAction 中就要有eat方法。
以上是最简化的实例,若对大家有帮助,我会很高兴,若有不对或好方法请多提意见。