Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Original solution

Introduction

Often, we have multiple submit buttons within a single form. The below is just a simple way of identifying which button was clicked, and which actions to take.

...

There are other ways to achieve the same functionality. There are pros and cons to each methods. Feedback welcome.

Nyong Nyong's solution

Note

This was originally taken from comment posted by Nyong Nyong to this page - you can see it here

The more elegant solution is probably by using multiple mappings for same Action.

In JSP

Code Block
html
html

<s:form method="post" action="mySubmitAction">
    <s:submit value="Submit"/>
    <s:submit value="Clear" action="myClearAction"/>
</form>

In struts.xml

Code Block
xml
xml

<action name="mySubmitAction" class="MyAction" method="submit">
       <result>submit.jsp</result>
</action>
<action name="myClearAction" class="MyAction" method="clear">
       <result>submit.jsp</result>
</action>

Then in MyAction class

Code Block

public String submit() throws Exception {
    // submit button logic here
    return SUCCESS;
}

public String clear() throws Exception {
    // clear button logic here
    return SUCCESS;
}


For best practice, if you have common data loaded / managed by your actions (submit & clear), then for example, you can define a MyBaseAction class, extended by MySubmitAction and MyClearAction class. Then this is how they looks like:

In struts.xml

Code Block
xml
xml

<action name="mySubmitAction" class="MySubmitAction">
       <result>submit.jsp</result>
</action>
<action name="myClearAction" class="MyClearAction">
       <result>submit.jsp</result>
</action>

You don't need to specify a method name anymore, that means we will use the default execute() method.

Then in the MyAction, MySubmitAction and MyClearAction class

Code Block
titleMyAction.java

public class MyAction extends ActionSupport {
    // common data or logic here
}
Code Block
titleMySubmitAction.java

public class MySubmitAction extends MyAction {

    public String execute() throws Exception {
        // submit button logic here
        return SUCCESS;
    }
}
Code Block
titleMyClearAction.java

public class MyClearAction extends MyAction {

    public String execute() throws Exception {
        // clear button logic here
        return SUCCESS;
    }
}