javascriptstruts2xml-configurationstruts-action

How to call a method in Struts 2 Action class with JavaScript?


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 Struts 2 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" >

Solution

  • 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 ;