Thymeleaf多个提交按钮在一个表单中

Lie*_* Do 20 java spring-mvc thymeleaf

我有一个带有一个表单和两个按钮的HTML页面片段:

<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>
Run Code Online (Sandbox Code Playgroud)

和控制器:

@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;
}
Run Code Online (Sandbox Code Playgroud)

这项工作很好,但如果我有更多按钮,我必须添加更多if语句来检查action字符串.还有另一种方法可以为表单中的每个按钮创建一个动作吗?

Kay*_*man 38

您可以@RequestMappings使用params变量创建不同的方法.

@RequestMapping(value="/edit", method=RequestMethod.POST, params="action=save")
public ModelAndView save() {}


@RequestMapping(value="/edit", method=RequestMethod.POST, params="action=cancel")
public ModelAndView cancel() {}
Run Code Online (Sandbox Code Playgroud)


Par*_*iya 10

这适用于我的问题。在提交按钮上使用th:formaction这是关于您有多少个提交按钮的工作,这对于为具有不同提交按钮的一个表单提供更多链接也很有用

<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>
Run Code Online (Sandbox Code Playgroud)


Gem*_*tic 6

如果您不想将每个选项都作为新的请求映射,那么您可以使用 switch case 代替 if-case。

@RequestMapping(value="/edit", method=RequestMethod.POST)
public ModelAndView edit(@ModelAttribute SomeModel model, 
        @RequestParam(value="action", required=true) String action) {
    switch(action) {
        case "save":
            // do stuff
            break;
        case "cancel":
            // do stuff
            break;
        case "newthing":
            // do stuff
            break;
        default:
            // do stuff
            break;
    }
}
Run Code Online (Sandbox Code Playgroud)