Spring 4 mvc multiple radio buttons example using hashmap / arraylist

In this tutorial, let us see how to implement multiple (i.e more than two) radio buttons using <form:radiobutton> or <form:radiobuttons> tag  with or without using Hashmap or Arraylist in Spring MVC web application. In this example, let us design a sample movie survey form for getting Input from the public.

radio button1

In the above form, 3 set of radio buttons are there.

1. To input Gender – Used <form:radiobutton>

2. To input Marital status – Used <form:radiobuttons> with array list

3. To input Favorite movie category – Used <form:radiobuttons> with hash map.

Let us see the differences

1. Using <form:radiobutton>:  Multiple separate statements are used in view to generate multiple radio buttons.

For example, in the above form to generate three Genders (Male, Female & Not Known) radio buttons, the below statements are used in view.

				<form:radiobutton path="gender" value="M" label="Male" id="gender"/>
				<form:radiobutton path="gender" value="F" label="Female" id="gender"/>
				<form:radiobutton path="gender" value="O" label="Not Known" id="gender"/>

2. Using <form:radiobuttons>  with array list: Single statement is used to display any number of radio buttons. Radio button label is captured in a arraylist. It is very easy to increase radio buttons in view by simply adding the radio button label in arraylist.

In the above form, to display list of maritalStatus as radio buttons, the below statement is used.

<form:radiobuttons path="maritalStatus" items="${maritalStatusList}" /> 

where maritalStatusList is an arraylist.

3. Using <form:radiobuttons> with hash map: Single statement is used to display any number of radio buttons. Radio button label is captured in a hashmap. When you want to display radio button label with value (id), we can use hashmap. The below statement is used to display list of movie categories with Id value.

<form:radiobuttons path="favoriteMovieType" items="${movieTypeList}" />  

where movieTypeList is a hashmap.

Now let us see the steps to create radio buttons using Spring 4.

Jars & Tools used in this tutorial

1. Spring 4.1.4

2. Java 1.8

3. hibernate-validator-5.1.3.Final.jar

4.  validation-api-1.1.0.Final.jar

5. jstl-1.2.jar

6. Eclipse with Apache server

Project Structure:

radio button project structure

Step 1: Design a web page as shown in the above image which is having the fields of name, age, maritalStatus and favoriteMovieType

The complete JSP Code (RadioButtonExample.jsp)

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"     pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
.error {
	color: #ff0000;

.errorblock {
	margin: 15px;
	color: #000;
	background-color: #ffEEE0;
	border: 3px solid #ff0000;

	<h2>Spring MVC RadioButton & RadioButtons  example</h2>

	<h3>Movie Survey Form</h3>

	<form:form method="POST" action="processSurvey.do" commandName="surveyForm">
		<form:errors path="*" cssClass="errorblock" element="div" />
            <td>Name <font color="red">*</font></td>
            <td><form:input path="name" id="name"/></td>
            <td><form:errors path="name" cssClass="error"/></td>
            <td><form:input path="age" id="age"/></td>
            <td><form:errors path="age" cssClass="error"/></td>

			<td>Are you <font color="red">*</font></td>
				<form:radiobutton path="gender" value="M" label="Male" id="gender"/>
				<form:radiobutton path="gender" value="F" label="Female" id="gender"/>
				<form:radiobutton path="gender" value="O" label="Not Known" id="gender"/>
			<td><form:errors path="gender" cssClass="error"/></td>

			<td>Are you  <font color="red">*</font></td>
			<td><form:radiobuttons path="maritalStatus" items="${maritalStatusList}" />	</td>
			<td><form:errors path="maritalStatus" cssClass="error"/></td>

			<td>Your favorite type of  movie <font color="red">*</font></td>
			<td><form:radiobuttons path="favoriteMovieType" items="${movieTypeList}" /></td>
			<td><form:errors path="favoriteMovieType" cssClass="error"/></td>

			<td colspan="4">.....</td>

				<td colspan="3"><input type="submit" /></td>

			<font color="red">*</font> Indicates Mandatory input



Step 2: Write java class (model) (SurveyForm.java) for mapping the fields of RadioButtonExample page.

package net.javaonline.spring.radio.form;

import org.hibernate.validator.constraints.NotEmpty;

public class SurveyForm {
	private String name;
	private String age;
	private String gender="M";
	private String maritalStatus="";
	private String favoriteMovieType="";

	public String getFavoriteMovieType() {
		return favoriteMovieType;
	public void setFavoriteMovieType(String favoriteMovieType) {
		this.favoriteMovieType = favoriteMovieType;
	public String getName() {
		return name;
	public void setName(String name) {
		this.name = name;
	public String getAge() {
		return age;
	public void setAge(String age) {
		this.age = age;
	public String getGender() {
		return gender;
	public void setGender(String gender) {
		this.gender = gender;
	public String getMaritalStatus() {
		return maritalStatus;
	public void setMaritalStatus(String maritalStatus) {
		this.maritalStatus = maritalStatus;


In the above code, all the fields except age is mandatory.
For default selection of the radio button, value of the radio button is assigned to the corresponding field. For example, the statement private String gender=”M”; makes the male radio button in Gender be selected by default.

Step 3: Write Controller class (SurveyController.java) to load radio button example page (RadioButtonExample.jsp) and process

package net.javaonline.spring.radio.controller;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import net.javaonline.spring.radio.form.SurveyForm;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

public class SurveyController {

	//For Radio Buttons using ArrayList
	public ArrayList getMaritalStatusList()
		ArrayList < String> maritalStatusList = new ArrayList<String>();

		return maritalStatusList;

	//For Radio Buttons using HashMap
	public Map movieTypeList()
		Map <String, String> movieTypeList = new HashMap<String, String>();

		return movieTypeList;

@RequestMapping(value = "/loadSurveyPg", method = RequestMethod.GET)
	public String loadSurveyPg(@ModelAttribute("surveyForm") SurveyForm surveyForm,Model model) {
	model.addAttribute("surveyForm", surveyForm);

	    return "RadioButtonExample";

@RequestMapping(value = "/processSurvey", method = RequestMethod.POST)
public String processSurvey(@Valid @ModelAttribute("surveyForm") SurveyForm surveyForm,BindingResult result,Model model,HttpSession session) throws ParseException {

	if (result.hasErrors()) {
		System.out.println("validation error occured in survey form");
        return "RadioButtonExample";
	// Processing and Storing  in the database.

	return "DataDisplay"; //to display submitted data


Step 4: Design a page (DataDisplay.jsp) to display the submitted data when the user submits the survey form with all mandatory inputs.


<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib uri='http://java.sun.com/jsp/jstl/core' prefix='c'%>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Radio Button Example Your Input</title>
<h3>Thank you for your Input for the Survey</h3>
<table border="1">
    	<td>Name  </td><td>${surveyForm.name} </td>
     	<td>Age </td> <td> ${surveyForm.age} </td>
      	<td>Gender </td> <td> ${surveyForm.gender} </td>
      	<td>Marital Status </td> <td> ${surveyForm.maritalStatus} </td>
      	<c:set var="key" value="${surveyForm.favoriteMovieType}" />
     	<td>Favorite Movie Type </td><td> ${movieTypeList[key]} </td>

In the above JSP,to display the hashmap value of a key, the below lines are used.

	<c:set var="key" value="${surveyForm.favoriteMovieType}" />
     	<td>Favorite Movie Type </td><td> ${movieTypeList[key]} </td>

– where the key is the selected radio button value i.e surveyForm.favoriteMovieType.

Step 5: Now copy the necessary XML files (web.xml, RadioButton-Context.xml) to your project.


<?xml version="1.0" encoding="UTF-8"?>

<web-app version="2.4"
         http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" >





<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"

      <context:component-scan base-package="net.javaonline.spring.radio.controller"/>
	  <mvc:annotation-driven />	

	  <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
        <property name="basename" value="messages"/>
	  <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/Pages/" />
        <property name="suffix" value=".jsp" />


In the project, Custom error messages are mentioned in the messages.properties

Compile and Run the project by calling the URL


radio button2radio button3


Fill all the fields and submit. 


radio button4

Submitted Data

radio button5

Reference : Spring-form.tld

The above project can be downloaded at SpringRadioButtonDemo.war

You may also like

Leave a Reply

Be the First to Comment!