I have a fragment of HTML page with one form and 2 button:
<form action="#" data-th-action="@{/action/edit}" data-th-object="${model}" method="post"> <button type="submit" name="action" value="save">save</button> <button type="submit" name="action" value="cancel">cancel</button> </form>
And the controller:
@RequestMapping(value="/edit", method=RequestMethod.POST) public ModelAndView edit(@ModelAttribute SomeModel model, @RequestParam(value="action", required=true) String action) { if (action.equals("save")) { // do something here } if (action.equals("cancel")) { // do another thing } return modelAndView; }
This work good, but if I have more button, I must add more if
statement to check the action
string. Is there another way that I can create one action for each button in the form?
Let's learn the steps of performing multiple actions with multiple buttons in a single HTML form: Create a form with method 'post' and set the value of the action attribute to a default URL where you want to send the form data. Create the input fields inside the as per your concern. Create a button with type submit.
yes, multiple submit buttons can include in the html form. One simple example is given below.
The only way I found is to build an other object containing those two objects, and pass it. That works well, but I can't create that kind of object, it's nonsense (even if it works). Of course, the objects aren't as simple as Foo and Bar here, otherwise I would have merge those two.
You can create separate methods with different @RequestMappings
using the params variable.
@RequestMapping(value="/edit", method=RequestMethod.POST, params="action=save") public ModelAndView save() {} @RequestMapping(value="/edit", method=RequestMethod.POST, params="action=cancel") public ModelAndView cancel() {}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With