一种形式的 Thymeleaf 多个提交按钮 [英] Thymeleaf multiple submit button in one form

查看:65
本文介绍了一种形式的 Thymeleaf 多个提交按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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>

和控制器:

@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;
}

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

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?

推荐答案

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

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() {}

这篇关于一种形式的 Thymeleaf 多个提交按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆