【问题标题】:How to call different methods defined in one action in struts2?如何在struts2中调用一个动作中定义的不同方法?
【发布时间】:2018-02-23 21:40:52
【问题描述】:

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

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

通过 ajax 调用 otherMethod() 的 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 调用:

$.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()方法?

【问题讨论】:

  • 我认为有一个带有感叹号的语法 - 比如/json/saveJSONDataAction!otherMethod.action

标签: java ajax struts2


【解决方案1】:

您可以在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

【讨论】:

  • 做同样的事情,但要加上注释。
【解决方案2】:

有一个功能叫Dynamic method invocation

动态方法调用 (DMI) 将使用“!”后面的字符串动作名称中的字符作为要调用(而不是执行)的方法的名称。对“Category!create.action”的引用表示使用“Category”动作映射,但改为调用 create 方法。

请注意,它可能会引入安全漏洞...因此请务必正确配置此行为(请参阅官方文档)。

【讨论】:

  • 你在说什么安全漏洞,更具建设性。
  • 没有strict-method-invocation可以调用任何方法。
猜你喜欢
  • 1970-01-01
  • 2015-12-08
  • 2017-10-09
  • 2016-06-29
  • 1970-01-01
  • 2015-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多