How to call different methods defined in one action in struts2?
Solution 1
There is a feature called Dynamic method invocation:
Dynamic Method Invocation (DMI) will use the string following a "!" character in an action name as the name of a method to invoke (instead of execute). A reference to "Category!create.action", says to use the "Category" action mapping, but call the create method instead.
Note, that it might introduce security hole... so be sure to configure this behavior properly (see the oficial documentation).
Solution 2
You can specify what method is executed in struts.xml
file. You just need to override the default, which is 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() -->
Then, you just need to call ../json/MySecondAction.action
in your function.
Roman
Updated on June 04, 2022Comments
-
Roman almost 2 years
I'm not familiar with struts2, but I know that method execute() is called as default in Action during call to action by name. But how to call other method defined in the same action class?
In an example below execute() method is called when I set url link in ajax like that:
saveJSONDataAction.action
thanks to @Action annotation.How the url should looks like to call otherMethod() by ajax?
Action class:
@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 call:
$.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'); } } });
How to call otherMethod() method by ajax?
-
Roman C almost 11 yearsDo it the same but with annotations.
-
Roman C almost 11 yearsWhat a security hole are you talking, be more constructive.
-
Pavel Horal over 10 yearsWithout
strict-method-invocation
it is possible to call any method.