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

Rom*_*man 2 java ajax struts2

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

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

网址应该如何通过ajax调用otherMethod()?

行动类:

@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
}
Run Code Online (Sandbox Code Playgroud)

Ajax调用:

$.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');
      }
    }
});
Run Code Online (Sandbox Code Playgroud)

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

Arm*_*don 5

您可以指定在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() -->
Run Code Online (Sandbox Code Playgroud)

然后,您只需要调用../json/MySecondAction.action您的函数.