Spring MVC Radiobutton And Radiobuttons Example

This is a simple example of how to use the radiobutton and radiobuttons tags in Spring MVC. Among the most famous HTML tags is the radio button tag, that renders one or multiple HTML input tags with type radio. The radiobutton and radiobuttons tags are pretty similar to the HTML radio button tag and they are very easy to use, as will be shown below.

In this example we have created a simple class, which is the MVC model. It has two properties, one String property to be used for the radiobutton tag and another String property to be used for the radiobuttons tag. We have also created a validator to check if the radiobuttons tag is checked. There is also a simple view that contains a form with the radiobutton and radiobuttons fields.pack

You may skip project creation and jump directly to the beginning of the example below.

Our preferred development environment is Eclipse. We are using Eclipse Juno (4.2) version, along with Maven Integration plugin version 3.1.0. You can download Eclipse from here and Maven Plugin for Eclipse from here. The installation of Maven plugin for Eclipse is out of the scope of this tutorial and will not be discussed. We are also using JDK 7_u_21. Tomcat 7 is the application server used.

Let’s begin,

1. Create a new Maven project

Go to File -> Project ->Maven -> Maven Project.

New Maven Project
New Maven Project – step 1

In the “Select project name and location” page of the wizard, make sure that “Create a simple project (skip archetype selection)” option is unchecked, hit “Next” to continue with default values.

New Maven project
New Maven project- step 2

Here the maven archetype for creating a web application must be added. Click on “Add Archetype” and add the archetype. Set the “Archetype Group Id” variable to "org.apache.maven.archetypes", the “Archetype artifact Id” variable to "maven-archetype-webapp" and the “Archetype Version” to "1.0". Click on “OK” to continue.

Add Maven archetype

In the “Enter an artifact id” page of the wizard, you can define the name and main package of your project. Set the “Group Id” variable to "com.javacodegeeks.snippets.enterprise" and the “Artifact Id” variable to "springexample". The aforementioned selections compose the main project package as "com.javacodegeeks.snippets.enterprise.springexample" and the project name as "springexample". Set the “Package” variable to "war", so that a war file will be created to be deployed to tomcat server. Hit “Finish” to exit the wizard and to create your project.

Configure Maven project
Configure Maven project

The Maven project structure is shown below:

New project structure
New project structure
    It consists of the following folders:
  • /src/main/java folder, that contains source files for the dynamic content of the application,
  • /src/test/java folder contains all source files for unit tests,
  • /src/main/resources folder contains configurations files,
  • /target folder contains the compiled and packaged deliverables,
  • /src/main/resources/webapp/WEB-INF folder contains the deployment descriptors for the Web application ,
  • the pom.xml is the project object model (POM) file. The single file that contains all project related configuration.

2. Add Spring-MVC dependencies

Add the dependencies in Maven’s pom.xml file, by editing it at the “Pom.xml” page of the POM editor. The dependency needed for MVC is the spring-webmvc package. The javax.validation and the hibernate-validator packages will be also used here for validation.


<project xmlns="" xmlns:xsi=""
	<name>springexample Maven Webapp</name>




3. Create the model

The class is the class created to be used as the Model. It has two properties, the String size and the String flavors. These fields will be used as the radiobutton and the radiobuttons fields.

package com.javacodegeeks.snippets.enterprise.radiobutton.model;

public class Order {

	String size;
	String flavors;

	public String getSize() {
		return size;

	public void setSize(String size) {
		this.size = size;

	public String getFlavors() {
		return flavors;

	public void setFlavors(String flavors) {
		this.flavors = flavors;

4. Create a Validator

The validator class that is created below is the class. It is used to help us check if at least one flavor is checked in the form. It implements the org.springframework.validation.Validator, and overrides the two methods it provides.

The boolean supports(Class<?> paramClass) method is used to check if the validator can validate instances of the paramClass.

In the validate(Object obj, Errors errors) method, an instance of the class is provided, and an Errors object. The org.springframework.validation.ValidationUtils is used here, since it offers validation API methods to check the fields of the object. So in this method we can check if the flavors field is empty. The error message is passed in the error object. A properties file with the error message is used here to pass the validation message to the errors object as shown below:

package com.javacodegeeks.snippets.enterprise.radiobutton.validator;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.javacodegeeks.snippets.enterprise.radiobutton.model.Order;

public class OrderValidator implements Validator {

		public boolean supports(Class<?> paramClass) {
			return Order.class.equals(paramClass);

		public void validate(Object obj, Errors errors) {
			ValidationUtils.rejectIfEmptyOrWhitespace(errors, "flavors", "valid.flavors");

The file below is the file that contains the error message for the flavors field of class.

valid.flavors = Please select at least one flavor for your ice cream!

5. Create the Controller

The Controller is where the DispatcherServlet will delegate requests. The @Controller annotation indicates that the class serves the role of a Controller. The @RequestMapping annotation is used to map a URL to either an entire class or a particular handler method.

A org.springframework.validation.Validator is injected here, via the @Autowired annotation, also making use of the @Qualifier annotation to specify that the implementation of the org.springframework.validation.Validator class is injected.

The @InitBinder annotation in initBinder(WebDataBinder binder) method allows us to configure web data binding directly within the controller. With @InitBinder we can inaitialize the WebDataBinder, that is used for data binding from web request parameters to JavaBean objects. Here, the WebDataBinder is where the validator is set.

The Controller consists of two basic methods, a GET method, which is String initForm(Model model) and a POST method, which is String submitForm(Model model, @Validated Order order, BindingResult result). The first method creates and returns to the "order" view a new instance of the class. Here we set the size field to big, so that it will have a pre-checked value in the form.

The second method also gets the Model, and the Order object created, which now consists of the values passed in the form. Order is annotated with the @Validated annotation, which allows the order object to be validated with the validator. BindingResult is where all validation errors are automatically passed, so it can be used to decide the next navigation step. If there are no errors, the validation is successful, so the method returns the String representation of the successOrder.jsp page, and the order object is passed at the Model. Otherwise, the returned String is the String representation of the order.jsp page, which also has the error messages, as will be shown below.

Take a look at the private void initModelList(Model model) method. It is used to initialize the list that is passed to the model for the radiobuttons tag. So every time the form is rendered the list of flavors for the radiobuttons tag is not null. If the list is not initialized, then the iteration over the items of the list leads to a NullPointerException.

package com.javacodegeeks.snippets.enterprise.radiobutton;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.javacodegeeks.snippets.enterprise.radiobutton.model.Order;

public class OrderController {

    private Validator validator;
    private void initBinder(WebDataBinder binder) {
	@RequestMapping(method = RequestMethod.GET)
	public String initForm(Model model) {
		Order order = new Order();
		model.addAttribute("order", order);
		return "order";

	@RequestMapping(method = RequestMethod.POST)
	public String submitForm(Model model, @Validated Order order, BindingResult result) {
		model.addAttribute("order", order);
		String returnVal = "successOrder";
		if(result.hasErrors()) {
			returnVal = "order";
		} else {
			model.addAttribute("order", order);
		return returnVal;

	private void initModelList(Model model) {
		List<String> flavorslist = new ArrayList<String>();
		model.addAttribute("flavors", flavorslist);

6. Create the view with the radiobutton and the radiobuttons fields

The view below is a simple example of how to create a form with an order. It is a simple html view consisting of the head and body html tags. In order to create a form in Spring MVC, we make use of the form:form tag. Its method property is set to POST, and the commandName property is set to the name of the backing bean that is binded to the Model, which is the class.

The form:radiobutton tag is used to create the radiobutton field, with its path property set to the field binded to it, which is the size field, and the value property set to a String value. We have created two form:radiobutton tags, both binded to the size property, but each one of them has a different value on its value property. The first one’s value property is set to "big". This radiobutton will be pre-checked, since in the Controller we have initialized the size property of the Order object, and we set it to "big".

The form:radiobuttons tag has another property to configure, appart from the path property. It also provides the items property, where the list of the items to be displayed is set. This is the list that is initialized in the initModelList(Model model)method of the Controller.

The form:errors tag defines where the error message of the specified field will be displayed in the view. Finally, the input tag, with type property set to submit is used for the submit button.


<%@ taglib prefix="form" uri=""%>
<title>Spring MVC radiobutton</title>

	<h2>Order your ice cream! </h2>

	<form:form method="POST" commandName="order">
				<td>Do you want the big size?</td>
				<td><form:radiobutton path="size" value="big"/> Yes
				 <form:radiobutton path="size" value="small"/> No </td>
				<td>Choose the flavor you like:</td>
				<td><form:radiobuttons path="flavors" items="${flavors}" /></td> 
				<td><form:errors path="flavors" cssStyle="color: #ff0000;"/></td>
				<td><input type="submit" name="submit" value="Submit"></td>


This page will be rendered when the submit button is pressed and the validation succeeds:


<%@ taglib prefix="form" uri=""%>

<title>Spring MVC radiobutton</title>

	<h2>You chose a ${order.size} ice cream with ${order.flavors} flavor</h2>


7. Configure the application

The files that we must configure in the application are the web.xml file and the mvc-dispatcher-servlet.xml file.

The web.xml file is the file that defines everything about the application that a server needs to know. It is placed in the /WEB-INF/ directory of the application. The <servlet> element declares the DispatcherServlet. When the DispatcherServlet is initialized, the framework will try to load the application context from a file named [servlet-name]-servlet.xml located in /WEB-INF/ directory. So, we have created the mvc-dispatcher-servlet.xml file, that will be explained below. The <servlet-mapping> element of web.xml file specifies what URLs will be handled by the DispatcherServlet.


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="" xmlns="" xmlns:web="" xsi:schemaLocation="" id="WebApp_ID" version="3.0"> <display-name>Archetype Created Web Application</display-name>

The mvc-dispatcher-servlet.xml file is also placed in WebContent/WEB-INF directory. The org.springframework.web.servlet.view.InternalResourceViewResolver bean is used as internal resource views resolver, meaning that it will find the jsp and html files in the WebContent/WEB-INF/ folder. We can also set properties such as prefix or suffix to the view name to generate the final view page URL. This is the file where all beans created, such as Controllers are placed and defined.

The <context:component-scan> tag is used, so that the Spring container will search for all annotated classes under the com.javacodegeeks.snippets.enterprise package. The <mvc:annotation-driven> tag is used, so that the container searches for annotated classes, to resolve MVC. The class is also defined here as a bean, with an id.

Finally, the ResourceBundleMessageSource is used, to provide access to resource bundles using specified basenames. Its basename property is set to validation, thus pointing to the properties file that holds the validation messages.


<beans xmlns="" 	xmlns:context="" xmlns:mvc="" xmlns:xsi="" xsi:schemaLocation="">

  <context:component-scan base-package="com.javacodegeeks.snippets.enterprise" />
  <mvc:annotation-driven />

	<bean id="messageSource"
		<property name="basename" value="validation" />

 <bean id="orderValidator" class="com.javacodegeeks.snippets.enterprise.radiobutton.validator.OrderValidator" />
		<property name="prefix">
		<property name="suffix">


8. Run the application

Now, let’s run the application. We first build the project with Maven. All we have to do is right click on the project and select -> Run As: Maven build. The goal must be set to package. The .war file produced must be placed in webapps folder of tomcat. Then, we can start the server.

Hit on:


The page rendered is the one below, and it has the "Yes" value pre-checked, which corresponds to the "big" value, as explained above:

Radiobutton page
Radiobutton page

Click on the Submit button. The result is the one below:

Radiobutton error
Radiobutton error

The validation message is displayed, since no flavor is checked.
Now, check on a flavor and click on Submit again:

Radiobutton correct
Radiobutton correct

Now the validation is correct and the successOrder page is rendered.

This was an example of how to use a radiobutton and a radiobuttons tag in a Spring MVC form.
Download the eclipse project of this tutorial: SpringMVCRadioButton

Theodora Fragkouli

Theodora has graduated from Computer Engineering and Informatics Department in the University of Patras. She also holds a Master degree in Economics from the National and Technical University of Athens. During her studies she has been involved with a large number of projects ranging from programming and software engineering to telecommunications, hardware design and analysis. She works as a junior Software Engineer in the telecommunications sector where she is mainly involved with projects based on Java and Big Data technologies.
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Back to top button