您的位置:首页 > 编程语言 > Java开发

action动态方法调用和使用通配符定义action

2013-04-21 20:39 676 查看
一。动态方法调用

如果Action中存在多个方法时,我们可以使用!+方法名调用指定方法。如下:

Java代码  



public class HelloWorldAction{  

    private String message;  

    ....  

    public String execute() throws Exception{  

        this.message = "我的第一个struts2应用";  

        return "success";  

    }  

      

    public String other() throws Exception{  

        this.message = "第二个方法";  

        return "success";  

    }  

}  

 假设访问上面action的URL路径为: /struts/test/helloworld.action要访问action的other() 方法,我们可以这样调用:

/struts/test/helloworld!other.action

通常不建议大家使用动态方法调用,我们可以通过常量struts.enable.DynamicMethodInvocation关闭动态方法调用。如下所示:

Xml代码  



<constant name="struts.enable.DynamicMethodInvocation" value="false"/>  

 二。使用通配符定义action

action代码如下所示:

Java代码  



public class HelloWorldAction{  

    private String message;  

    ....  

    public String execute() throws Exception{  

        this.message = "我的第一个struts2应用";  

        return "success";  

    }  

      

    public String other() throws Exception{  

        this.message = "第二个方法";  

        return "success";  

    }  

}  

 配置文件如下:

Xml代码  



<package name="itcast" namespace="/test" extends="struts-default">  

    <action name="helloworld_*" class="cn.itcast.action.HelloWorldAction" method="{1}">  

        <result name="success">/WEB-INF/page/hello.jsp</result>  

    </action>  

</package>  

 其中的helloworld_*中的下划线(_)并不是必须的,因为helloworld_*中只有一个通配符*,所以method="{1}",也可以是helloworld_*_*,则method="{1}_{2}",class和result中也可以使用通配符的值,如:class="cn.itcast.action.{1}HelloWorldAction",    <result name="success">/WEB-INF/page/{1}hello.jsp</result>.

此时要访问action中的other()方法,可以通过这样的URL访问:/test/helloworld_other.action
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  struts2 web