struts2中如何调用一个action中定义的不同方法?

2024-03-10

我不熟悉struts2,但我知道在按名称调用操作期间,Action 中默认调用方法execute() 。但是如何调用同一个动作类中定义的其他方法呢?

在下面的示例中,当我在ajax中设置url链接时,会调用execute()方法,如下所示:saveJSONDataAction.action感谢@Action注释。

通过 ajax 调用其他 Method() 的 url 应该是什么样子?

动作类:

@ParentPackage("json-default")
@Action(value="getJSONDataAction")
@Result(name="success", type="json")
public class JSONDataAction extends ActionSupport {
    private static final long serialVersionUID = 1L;

    private List<Report> data = new ArrayList<Report>();

    public JSONDataAction(){
        data.add(new Report(1, "Chris", true, "2008-01-01", "orange"));
    }

    public String execute() {
        return SUCCESS;
    }

    public String otherMethod() {
        //do something else ..
        return SUCCESS;
    }

    // getters and setters
}

阿贾克斯调用:

$.ajax({
    url: "../json/saveJSONDataAction.action",
    data: data,
    dataType: 'json',
    contentType: 'application/json',
    type: 'POST',
    success: function (res) {
      if (res.result === 'ok') {
        $console.text('Data saved');
      }
    }
});

如何通过ajax调用otherMethod()方法?


您可以指定执行什么方法struts.xml文件。您只需要覆盖默认值,即execute.

<action name="MyMainAction" class="foo.bar.MyAction">
     <result>result.jsp</result>
</action>
<!-- This will call execute() -->

<action name="MySecondAction" class="foo.bar.MyAction" method="secondExecute">
     <result>result.jsp</result>
</action>
<!-- This will call secondExecute() -->

然后,你只需要调用../json/MySecondAction.action在你的函数中。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

struts2中如何调用一个action中定义的不同方法? 的相关文章

随机推荐