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"%>
<html>
<head>
<style>
.error {
	color: #ff0000;
}

.errorblock {
	padding:10px;
	margin: 15px;
	color: #000;
	background-color: #ffEEE0;
	border: 3px solid #ff0000;
}
</style>
</head>

<body>
	<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" />
	<table>
	 <tr>
            <td>Name <font color="red">*</font></td>
            <td><form:input path="name" id="name"/></td>
            <td><form:errors path="name" cssClass="error"/></td>
        </tr>
        <tr>
            <td>Age</td>
            <td><form:input path="age" id="age"/></td>
            <td><form:errors path="age" cssClass="error"/></td>
        </tr>

    	<tr>
			<td>Are you <font color="red">*</font></td>
			<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>
			<td><form:errors path="gender" cssClass="error"/></td>
		</tr>

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

       	<tr>
			<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>
		</tr>

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

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

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

	</form:form>

</body>
</html>
</html>

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 {
	@NotEmpty
	private String name;
	private String age;
	@NotEmpty
	private String gender="M";
	@NotEmpty
	private String maritalStatus="";
	@NotEmpty
	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;

@Controller
public class SurveyController {

	//For Radio Buttons using ArrayList
	@ModelAttribute("maritalStatusList")
	public ArrayList getMaritalStatusList()
	{
		ArrayList < String> maritalStatusList = new ArrayList<String>();
		maritalStatusList.add("Single");
		maritalStatusList.add("Married");
		maritalStatusList.add("Widow");
		maritalStatusList.add("Divorced");

		return maritalStatusList;
	}	

	//For Radio Buttons using HashMap
	@ModelAttribute("movieTypeList")
	public Map movieTypeList()
	{
		Map <String, String> movieTypeList = new HashMap<String, String>();
		movieTypeList.put("1","Comedy");
		movieTypeList.put("2","Action");
		movieTypeList.put("3","Horror");
		movieTypeList.put("4","Thriller");
		movieTypeList.put("5","Animation");
		movieTypeList.put("6","Drama");
		movieTypeList.put("7","SAD");

		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.

DataDisplay.jsp

<%@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'%>

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

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.

web.xml

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

<web-app version="2.4"
         xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
         http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" >

  <servlet>
    <servlet-name>RadioButton</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
     <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/RadioButton-Context.xml</param-value>
      </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>

 <servlet-mapping>
    <servlet-name>RadioButton</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>

</web-app>

RadioButton-Context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:context="http://www.springframework.org/schema/context"
      xmlns:mvc="http://www.springframework.org/schema/mvc"
      xmlns:tx="http://www.springframework.org/schema/tx"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.1.xsd">

      <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>
	  <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/Pages/" />
        <property name="suffix" value=".jsp" />
    </bean>

</beans>

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

Compile and Run the project by calling the URL

http://localhost:8080/SpringRadioButtonDemo/loadSurveyPg.do

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