今天遇见一个form需要两个button提交显示不同Controller的需求
一开始解决思路:
我有一个HTML页面的一个窗体和2个按钮的片段:
<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>
以及控制器:
@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;
}
后来网上查阅大牛的思路:
您可以使用params变量创建具有不同@RequestMappings的单独方法。
@RequestMapping(value="/edit", method=RequestMethod.POST, params="action=save")
public ModelAndView save() {}
@RequestMapping(value="/edit", method=RequestMethod.POST, params="action=cancel")
public ModelAndView cancel() {}
使用th:formactionon submit button这是工作在多少你有submit button和这也是usefull给予更多的链接到一个表单与不同的submit button
<form action="#" class="form" th:action="@{'/publish-post/'+${post.id}}" method="post">
<input class="savebtn" type="submit" value="Save" th:formaction="'/save-post/'+${post.id}">
<input class="publish" type="submit" value="Publish Article">
</form>
对于多个提交按钮,下面的方法对我很有效。* 注意:th:取消按钮中的格式操作。*
<form action="#" th:action="@{/saveProducts}" th:object="${model}" method="post"><button type="submit" name="action" value="cancel" th:formaction="@{/cancelProducts}">CANCEL</button><button type="submit" name="action" value="save">SAVE</button>
</form>
对于控制器:
@RequestMapping(value="/saveProducts", method= RequestMethod.POST)public String save(@ModelAttribute SomeModel model) {*//Do something*}@RequestMapping(value="/cancelProducts", method=RequestMethod.POST)public String cancel(@ModelAttribute SomeModel model) {*//Do something*}