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.
 

Related Whitepaper:

Introduction to Web Applications Development

Kick start your web apps development with this introductory ebook!

This 376 page eBook 'Introduction to Web Applications Development', starts with an introduction to the internet, including a brief history of the TCT/IP protocol and World Wide Web. It defines the basic concepts for web servers and studies the case of Apache, the most used webserver, while other free software webservers are not forgotten. It continues with webpage design focusing on HTML and JavaScript. XML Schemas, their validation and transformation are covered as well as dynamic webpages built with CGI, PHP or JSP and database access.

Get it Now!  

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


+ 5 = twelve



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use
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.

Sign up for our Newsletter

15,153 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books