12

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.

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.

Any help or suggestions?

1
  • @axtavt: just to provide more information, I struggle with formCheckboxes as well, and eventually abandoned it. Spring binding is not well-supported for checkboxes Commented Jan 3, 2012 at 3:38

2 Answers 2

21

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

<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)
{
    ...
}
Sign up to request clarification or add additional context in comments.

1 Comment

the optional attribute in the @RequestParam is no longer valid, this can be replaced with required
1

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 not checked, the variable is not submitted at all.

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.

1 Comment

Spring does do something about this - see stackoverflow.com/questions/8723765/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.