Alexey Zvolinskiy

About 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 two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.

3 Responses to "Spring MVC: form handling vol. 3 – checkboxes processing"

  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


− one = 7



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

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

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close