我不熟悉struts2,但我知道方法execute()在按名称调用操作期间在Action中被默认调用。但是如何调用同一动作类中定义的其他方法?
在下面的示例中,当我在ajax中设置url link时调用了execute()方法:saveJSONDataAction.action
感谢@Action注释。
url应该如何通过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
}
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');
}
}
});
如何通过ajax调用otherMethod()方法?
答案 0 :(得分: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() -->
然后,您只需要在函数中调用../json/MySecondAction.action
。
答案 1 :(得分:3)
有一项名为Dynamic method invocation的功能:
动态方法调用(DMI)将使用“!”后面的字符串动作名称中的字符作为要调用(而不是执行)的方法的名称。对“Category!create.action”的引用表示使用“类别”动作映射,而是调用create方法。
请注意,它可能会引入安全漏洞......所以请务必正确配置此行为(请参阅官方文档)。