How to call a method in Struts2 Action Class method with javascript

ponder275 picture ponder275 · Mar 3, 2016 · Viewed 10.9k times · Source

We currently use the following javascript to submit the form when one of the field values change.

var url = "project/location/myAction.action?name="+ lname ; 
document.forms[0].action = url;
document.forms[0].submit();

which calls the following Struts2 action

<action name="myAction" class="project.location.NameAction">
    <result name="success" type="tiles">myAction</result>   
</action>

which then goes to the execute() method of the Action class NameAction where I have to check to see if the form was submitted from the javascript.

I would prefer to call the findName() method in NameAction directly from the javascript. In other words I want the javascript to act like the following jsp code.

<s:submit method="findName" key="button.clear" cssClass="submit" >

Answer

Andrea Ligios picture Andrea Ligios · Mar 3, 2016

There are different ways to achieve what you want, but probably the simpler is to map different actions to different methods of the same action class file, eg. with annotations:

public class NameAction {

    @Action("myAction")
    public String execute(){ ... }

    @Action("myActionFindName")
    public String findName(){ ... }

}

or with XML:

<action name="myAction" class="project.location.NameAction">
    <result name="success" type="tiles">myAction</result>   
</action>

<action name="myActionFindName" class="project.location.NameAction" method="findName">
    <result name="success" type="tiles">myAction</result>   
</action>

Then in javascript:

var url = "project/location/myActionFindName.action?name="+ lname ;