Monday, February 18, 2013

SpringMVC Form Tag Lib Checkbox + Checkboxs

For binding data on a jsp page to a form, one of the easiest ways is using spring form tag.
In this article, I will show you how to bind form data by using:
  • <form:checkbox>
  • <form:checkboxes>

1. Form Bean


public class User {

 // a check box
 private boolean married;

 // checkboxs
 private String[] hobbies;
....
}

To store status of multi checkbox, we must use a array of String.

2. Form Tags


To generate a checkbox, we use this syntax:
<form:label path="married">Married</form:label>
<form:checkbox path="married" /> 

  • form:label path="married" means generate a label for user.married
  • form:checkbox path="married" generated the checkbox

To generate a list of checkbox button, we use this syntax:
<form:checkboxes 
 path="hobbies" 
 items="${lstHobby}" 
/>

  • path="hobbies" means the selected checkbox values bind to hobbies attribute
  • items="${lstHobby}" means the check value and checkbox label are stored in lstHobby

4. In Controller

We initialize the item list in GET method
@RequestMapping(value = "/modifyUser", method = RequestMethod.GET)
public ModelAndView modifyUser() {

  Map<String, String> lstHobby = new HashMap<String, String>();
 lstHobby.put("1", "Music");
 lstHobby.put("2", "Game");
 lstHobby.put("3", "Reading");

 ModelAndView modelView = new ModelAndView("modifyUser");
 modelView.addObject("lstHobby", lstHobby);
 modelView.addObject("user", this.user);
  
 return modelView;
} 

As you see, the lstHobby is a Map, the key of Map is checkbox value and the value of Map is checkbox label

Note
The order of items is not guaranteed in JSP

References:
Source code:
  • For the demonstration, please download source code from HERE
  • My repository on Github

No comments:

Post a Comment