Home » Java » Enterprise Java » Spring MVC: form handling vol. 3 – checkboxes processing

About Alexey Zvolinskiy

Alexey Zvolinskiy
Alexey is a test developer with solid experience in automation of web-applications using Java, TestNG and Selenium. He is so much into QA that even after work he provides training courses for junior QA engineers.

Spring MVC: form handling vol. 3 – checkboxes processing

I have already published the post about processing of ‘checkbox’ tag using Spring MVC tag library. Now I want to develop this theme and proceed with the ‘checkboxes’ tag. It’s not much harder, but in some cases you’d better to use it. In this article I will provide examples of Spring ‘checkboxes’ tag in conjunction with java.util.List and java.util.Map, so be ready to examine two examples.

Before I start demonstrate the examples, I want to talk about a purpose of the ‘checkboxes’ tag. So when you should use it? The answer is obvious, if you want to generate your checkboxes in a runtime
 
you have to use the ‘checkboxes’ tag. This will help you to avoid hardcoded values in JSPs. The ‘checkboxes’ tag can collaborate with arrays and java.util.Collection’s. Further I’m going examine two cases with the List and Map.

List and ‘checkboxes’ tag

The first example will be with the List. As in previous article I have to create a POJO and declare there desired List property with appropriate getter and setter methods.

public class FootballTeams {

private List teamsList;

public List getTeamsList() {
return teamsList;
}

public void setTeamsList(List teamsList) {
this.teamsList = teamsList;
}

}

After I created the domain model, I should develop controller with two methods – the one for navigation on a page with checkboxes, and another for processing of the checkboxes.

@Controller
public class FootballController {

@RequestMapping(value="/football-page")
private ModelAndView footballPage() {
ModelAndView mav = new ModelAndView("football-form");

List teams = new ArrayList();
teams.add("Bavaria Munich");
teams.add("Borussia Dortmund");
teams.add("Real Madrid");
teams.add("Barcelona");

mav.addObject("teamsList", teams);
mav.addObject("footballTeams", new FootballTeams());

return mav;
}

@RequestMapping(value="/football-result")
private ModelAndView processTeams(@ModelAttribute FootballTeams footballTeams) {
ModelAndView mav = new ModelAndView("football-result");
mav.addObject("footballTeams", footballTeams);	
return mav;
}

}

Notice that in the footballPage() method I created the list of teams, and then I added it to the model. The second method doesn’t contain something special, so I don’t want consider it. Now let’s examine snippets of the views:

...
<h1>Football page</h1>
<form:form method="POST" commandname="footballTeams" action="football-result.html">
<table>
    <tbody><tr>
    <td>
<ul>
<form:checkboxes element="li" path="teamsList" items="${teamsList}">
</form:checkboxes></ul>
    </td>
    </tr>
    <tr>
        <td>
            <input value="Submit" type="submit">
        </td>
    </tr>
</tbody></table>
</form:form>
...

Here I need to make a pause and explain what’s going on. In the ‘checkboxes’ tag I specified the path attribute. The value of the attribute corresponds to the appropriate field of the FootballTeams class. The items attribute contains value of the list, which I generated in the controller’s footballPage() method.
The last one view:

...
<h1>Football result page</h1>
Selected teams:
<br>
<c:foreach var="team" items="${footballTeams.teamsList}">
${team}<br>
</c:foreach>
...

Here I just go through items which were selected on the previous page. Pay your attention that labels and values for the checkboxes were the same, as I specified in the list. If you want to have the different value and label for one checkbox, you have to use java.util.Map.

Map and ‘checkboxes’ tag

The second example will be with the Map. So as you suppose I’m going to show how to use different values and labels for same checkboxes. The structure of the section will be the same as in the previous one, so let’s start!

Domain model:

public class Tourism {

private List countries;

public List getCountries() {
return countries;
}

public void setCountries(List countries) {
this.countries = countries;
}

}

Don’t panic, that you didn’t see any Map field in the class, you will recognize this later.

@Controller
public class TourismController {

@RequestMapping(value="/tourism-page")
private ModelAndView tourismPage() {
ModelAndView mav = new ModelAndView("tourism-form");

Map countries = new HashMap();
countries.put("UKR", "Ukraine");
countries.put("ENG", "England");
countries.put("USA", "United States");

mav.addObject("countriesMap", countries);
mav.addObject("tourism", new Tourism());

return mav;
}

@RequestMapping(value="/tourism-result")
private ModelAndView processTourism(@ModelAttribute Tourism tourism) {
ModelAndView mav = new ModelAndView("tourism-result");
mav.addObject("tourism", tourism);	
return mav;
}

}

Here in the tourismPage() method Map appears on a scene.

...
<h1>Tourism page</h1>
<form:form method="POST" commandname="tourism" action="tourism-result.html">
<table>
    <tbody><tr>
    <td>
<ul>
<form:checkboxes element="li" path="countries" items="${countriesMap}">
</form:checkboxes></ul>
    </td>
    </tr>
    <tr>
        <td>
            <input value="Submit" type="submit">
        </td>
    </tr>
</tbody></table>
</form:form>
...

Map’s keys will be used as values of checkboxes, and Map’s values will be used as labels of checkboxes.

...
<h1>Tourism result page</h1>
Selected countries:
<br>
<c:foreach var="country" items="${tourism.countries}">
${country}<br>
</c:foreach>
...

It’s time to explain, why there is no Map field in the Tourism class. As you see, just Map’s keys are displayed on the result page. So key-value pairs are not passed to the model.

Summary

From the tutorial you can make a conclusion when ‘checkboxes’ tag is better to use. Spring MVC is very flexible framework, and it provides certain tools for the certain tasks. Use Map or List depending on aims. The source code you can see on the GitHub.
 

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

and many more ....

3 comments

  1. In the real world examples you would show how to pass all possible checkbox values, than how to the collection from the form object to this values :)

Leave a Reply

Your email address will not be published. Required fields are marked *

*


five × 4 =

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Do you want to know how to develop your skillset and become a ...

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!
Get ready to Rock!
To download the books, please verify your email address by following the instructions found on the email we just sent you.

THANK YOU!

Close