Java Spring MVC 和复选框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2060839/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 03:06:01  来源:igfitidea点击:

Spring MVC and Checkboxes

javaspringspring-mvc

提问by GaryF

I'm using Spring MVC 3.0 and can't quite see all the parts to this problem: my controller will produce a list of domain objects. Let's say a simple User object with firstName, lastName, age, and role properties. I want to output that list of users in a table (one column per property), each row also having a checkbox which are all selected by default. The person using the page can then potentially deselect some of them. When they hit the submit button, I'd like to be able to take the list of selected users and do something with them.

我正在使用 Spring MVC 3.0 并且不能完全看到这个问题的所有部分:我的控制器将生成一个域对象列表。假设一个简单的 User 对象具有 firstName、lastName、age 和 role 属性。我想在表中输出该用户列表(每个属性一列),每行还有一个复选框,默认情况下全部选中。然后,使用该页面的人可以取消选择其中的一些。当他们点击提交按钮时,我希望能够获取选定用户的列表并对其进行处理。

I know there is a form:checkboxes tag in Spring, but I can't quite see how to use it and how to get the results in the controller.

我知道 Spring 中有一个 form:checkboxes 标记,但我不太清楚如何使用它以及如何在控制器中获取结果。

Any help or suggestions?

任何帮助或建议?

采纳答案by axtavt

If you Userobject has an idfield, you can submit ids of selected users like this (you don't even need Spring's form tag for this simple scenario):

如果您的User对象有一个id字段,您可以像这样提交所选用户的 id(对于这个简单的场景,您甚至不需要 Spring 的表单标签):

<form ...>
    <c:foreach var = "user" items = "${users}">
        <input type = "checkbox" name = "userIds" value = "${user.id}" checked = "checked" /> <c:out value = "${user.firstName}" /> ...
    </c:foreach>
    ...
</form>

--

——

@RequestMapping (...)
public void submitUsers(@RequestParam(value = "userIds", required = false) long[] userIds)
{
    ...
}

回答by Kamyar Gilak

When a page contains a checkbox, and its containing form is submitted, browsers do the following.

当页面包含一个复选框,并且提交了它的包含表单时,浏览器会执行以下操作。

  • if the checkbox is checked, it is submitted with its 'value' attribute as a the value
  • if the checkbos is notchecked, the variable is not submitted at all.
  • 如果复选框被选中,则提交它的“值”属性作为值
  • 如果选中checkbos,则根本不提交变量。

In your case, i would change @RequestParam("abono") to @RequestParam(required=false, value="abono") and then check for your Boolean to be null. If it is null, the checkbox was not ticked by the user.

在您的情况下,我会将 @RequestParam("abono") 更改为 @RequestParam(required=false, value="abono") 然后检查您的布尔值是否为空。如果为空,则用户未勾选复选框。