Struts.xml中Action的method与路径的三种匹配方法

原文  http://blog.csdn.net/woshixuye/article/details/7734482

首先我们有一个Action——UserAction

public class UserAction extends ActionSupport 

    public String add() 
    { 
        return "add"; 
    }

    public String modify() 
    { 
        return "modify"; 
    } 
}


1 指定method

<package name="user" namespace="/userPath" extends="struts-default"> 
   <action name=" userAdd " class="com.xy.UserAction" method="add"> 
    <result name="add">add.jsp</result> 
   </action> 
   <action name=" userModify " class="com.xy.UserAction" method="modify"> 
    <result name="modify">modify.jsp</result> 
   </action> 
</package>

路径: 
userPath/userAdd 
userPath/userModify

特点: 
不灵活,CRUD四个操作就要配4个action。

2 动态方法调用DMI(Dynamic Method Invocation)

<package name="user" namespace="/userPath" extends="struts-default"> 
   <action name="user" class="com.xy.UserAction"> 
    <result name="add">add.jsp</result> 
 <result name="modify">modify.jsp</result> 
   </action> 
</package>

路径: 
userPath/user!add 
userPath/user!modify

特点: 
灵活。只要指定不同的方法就可以做不同的操作。

3 通配符

<package name="all" namespace="/" extends="struts-default"> 
   <action name="*_*" class="com.xy.{1}Action" method="{2}"> 
 <result name="add">{1}_add.jsp</result> 
 <result name="modify">{1}_modify.jsp</result> 
   </action> 
</package>

路径: 
User_add 
User_modify

特点: 
更加灵活。整个项目甚至只要配一个总的action。是指定方法的一个特殊的用法。不过我觉得用DMI可以将每个模块分的清楚。

推荐的方法是动态调用,也就是DMI.

 注意的问题:

1.比如在地址栏中输入URL:http://localhost:8080/struts2/front/helloword!add

但是:如果这样输入的话,会报错(There is no Action mapped for namespace [/front] and action name [helloword!add()] associated with context path [/Struts2_10003].)
因为:struts2中默认不允许使用DMI

所以:需要在配置文件中打开: <constant name="struts.enable.DynamicMethodInvocation" value="true"/>这样大家在地址栏动态输入就可以得到预期的页面

2.如果想要利用DMI的方式传递参数的话:userPath/user!add?flag=true

原文地址:https://www.cnblogs.com/hujunzheng/p/4603207.html