Spring MVC radiobutton and radiobuttons example
In Spring MVC, <form:radiobutton /> is used to render a HTML radio button, and the radio button values are hard coded inside the JSP page; While the <form:radiobuttons /> is used to render multiple radio buttons, and the radio button values are generated at runtime.
In this tutorial, we show you how to use <form:radiobutton /> and <form:radiobuttons />.
1. <form:radiobutton />
Generate a radio button, and hard-coded the value.
public class Customer{
String sex;
//...
}
<form:radiobutton path="sex" value="M"/>Male
<form:radiobutton path="sex" value="F"/>Female
To make the “Male” as the default selected value in above radio buttons, just set the “sex” property to “M“, for example :
public class Customer{
String sex = "M";
//...
}
or
//SimpleFormController...
@Override
protected Object formBackingObject(HttpServletRequest request)
throws Exception {
Customer cust = new Customer();
//Make "Male" as the default radio button selected value
cust.setSex("M");
return cust;
}
2. <form:radiobuttons />
Generate multiple radio buttons, and the values are generated at runtime.
//SimpleFormController...
protected Map referenceData(HttpServletRequest request) throws Exception {
Map referenceData = new HashMap();
List<String> numberList = new ArrayList<String>();
numberList.add("Number 1");
numberList.add("Number 2");
numberList.add("Number 3");
numberList.add("Number 4");
numberList.add("Number 5");
referenceData.put("numberList", numberList);
return referenceData;
}
<form:radiobuttons path="favNumber" items="${numberList}" />
To make the “Number 1” as the default selected value in above radio buttons, just set the “favNumber” property to “Number 1“, for example :
public class Customer{
String favNumber = "Number 1";
//...
}
or
//SimpleFormController...
@Override
protected Object formBackingObject(HttpServletRequest request)
throws Exception {
Customer cust = new Customer();
//Make "Number 1" as the default radio button selected value
cust.setFavNumber("Number 1")
return cust;
}
For radio button selection, as long as the “path” or “property” is equal to the “radio button value“, the radio button will be selected automatically.
Full radio button example
Let’s go thought a complete Spring MVC radio button example :
1. Model
A customer model class to store the radio button value.
File : Customer.java
package com.mkyong.customer.model;
public class Customer{
String favNumber;
String sex;
public String getFavNumber() {
return favNumber;
}
public void setFavNumber(String favNumber) {
this.favNumber = favNumber;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
2. Controller
A SimpleFormController
to handle the form radio button value. Make the radio button “M” as the default selected value.
File : RadioButtonController.java
package com.mkyong.customer.controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import com.mkyong.customer.model.Customer;
public class RadioButtonController extends SimpleFormController{
public RadioButtonController(){
setCommandClass(Customer.class);
setCommandName("customerForm");
}
@Override
protected Object formBackingObject(HttpServletRequest request)
throws Exception {
Customer cust = new Customer();
//Make "Make" as default radio button checked value
cust.setSex("M");
return cust;
}
@Override
protected ModelAndView onSubmit(HttpServletRequest request,
HttpServletResponse response, Object command, BindException errors)
throws Exception {
Customer customer = (Customer)command;
return new ModelAndView("CustomerSuccess","customer",customer);
}
protected Map referenceData(HttpServletRequest request) throws Exception {
Map referenceData = new HashMap();
List<String> numberList = new ArrayList<String>();
numberList.add("Number 1");
numberList.add("Number 2");
numberList.add("Number 3");
numberList.add("Number 4");
numberList.add("Number 5");
referenceData.put("numberList", numberList);
return referenceData;
}
}
3. Validator
A simple form validator to make sure the “sex” and “number” radio button is selected.
File : RadioButtonValidator.java
package com.mkyong.customer.validator;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import com.mkyong.customer.model.Customer;
public class RadioButtonValidator implements Validator{
@Override
public boolean supports(Class clazz) {
//just validate the Customer instances
return Customer.class.isAssignableFrom(clazz);
}
@Override
public void validate(Object target, Errors errors) {
Customer cust = (Customer)target;
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "sex", "required.sex");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "favNumber", "required.favNumber");
}
}
File : message.properties
required.sex = Please select a sex!
required.favNumber = Please select a number!
4. View
A JSP page to show the use of Spring’s form tag <form:radiobutton /> and <form:radiobuttons />.
File : CustomerForm.jsp
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<style>
.error {
color: #ff0000;
}
.errorblock {
color: #000;
background-color: #ffEEEE;
border: 3px solid #ff0000;
padding: 8px;
margin: 16px;
}
</style>
</head>
<body>
<h2>Spring's form radio button example</h2>
<form:form method="POST" commandName="customerForm">
<form:errors path="*" cssClass="errorblock" element="div" />
<table>
<tr>
<td>Sex :</td>
<td><form:radiobutton path="sex" value="M" />Male <form:radiobutton
path="sex" value="F" />Female</td>
<td><form:errors path="sex" cssClass="error" /></td>
</tr>
<tr>
<td>Choose a number :</td>
<td><form:radiobuttons path="favNumber" items="${numberList}" />
</td>
<td><form:errors path="favNumber" cssClass="error" /></td>
</tr>
<tr>
<td colspan="3"><input type="submit" /></td>
</tr>
</table>
</form:form>
</body>
</html>
Use JSTL to loop over the submitted radio button values, and display it.
File : CustomerSuccess.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<body>
<h2>Spring's form radio button example</h2>
Sex : ${customer.sex}
<br /> Favourite Number : ${customer.favNumber}
<br />
</body>
</html>
5. Spring Bean Configuration
Link it all ~
<beans xmlns="http://www.springframework.org/schema/beans"
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-2.5.xsd">
<bean
class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" />
<bean class="com.mkyong.customer.controller.RadioButtonController">
<property name="formView" value="CustomerForm" />
<property name="successView" value="CustomerSuccess" />
<!-- Map a validator -->
<property name="validator">
<bean class="com.mkyong.customer.validator.RadioButtonValidator" />
</property>
</bean>
<!-- Register the Customer.properties -->
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="message" />
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
6. Demo
Access the page – http://localhost:8080/SpringMVCForm/radiobutton.htm
If the user did not select any radio button value while submitting the form, display and highlight the error message.
If the form is submitted successfully, just display the submitted radio button values.
any post on how to make slider range dynamic? using thymeleaf
How we do this with spring 4 .. there are many changes and there is no SimpleFormController class
hi.. how to call validator class from controller class itself ??
This code is not working..
Hi,I think this was a good example and exlipans a lot about check boxes and radio buttons.But I am having a tough time displaying an image as the content of the radiobutton. This next line will make it clear:(0) Image1(0) Image2Is it possible to add image in such a manner to a radiobutton? If Yes, how? I have to do the same to checkbox also. Is it possible for checkbox? If yes how?
Your tutorial works well. However, if I try to map a springform radiobutton value which is mapped to a Java long datatype, it doesn’t seem to work. For example, here:
…whichHalf is a Java “long” datatype, which has only 4 valid numbers. My question is, how can I make this work without having to change the Java datatype to String?
I think I have solved the problem: I had 2 versions of a jsp representing the same object and somehow one of the version had bits missings.
Thanks.
How can I get the value of selected radio button out of the radioButtons in my controller..I want to use it..Please advise..Or is it possible to drive certain text boxes in spring on selection of a radio button…? I tried but during validation it is causing problem?
Hi..
I am using the form:select tag.I could not find any way to select all the options by default.
I want to select all the countries by default.
Please advise.
Thanks
Thanks for all your tutorials. It is very helpful!
I am following your tutorial and I wanted to display the radio buttons vertically instead of horizontally. Can you please let me know what changes I need to make?
Thanks,
Krish
Hello Mkyoug,
I found the answer!
I used foreach, .key, and .value
Thanks,
Krish
Thanks for your extra inputs.
Hi, when I run this example I got this error :
java.lang.NullPointerException
org.apache.jsp.WEB_002dINF.pages.CustomerForm_jsp._jspInit(CustomerForm_jsp.java:33)
org.apache.jasper.runtime.HttpJspBase.init(HttpJspBase.java:52)
org.apache.jasper.servlet.JspServletWrapper.getServlet(JspServletWrapper.java:159)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:329)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:236)
org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:257)
org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1183)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:902)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:807)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:571)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:501)
javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
Hi,
Thank you for this site, I am learning lot from it.
I noticed that all of your projects are maven, I used download a war or a spring project then import it in eclipse.
1)Please how did create this project (and others) to be a maven project (pom.xml) ?
2)I downloaded this project : SpringMVCForm-RadioButton-Example.zip
unzipped it, how to open it in eclipse.
Please your help is appreciated.
Thanks
Akram
Yes, Maven is simple and nice.
1. Learn Maven.
2. Download the project, find where is pom.xml file, and type “mvn eclipse:eclipse” to convert to Eclipse project, at the same time download the entire project dependencies.
Thank you,
Download the project, then mvn eclipse:eclipse,
Then should we import it as an existing project in eclipse ?
Does eclipse get all the jars downloaded automatically ?
Thanks
Maven will download it, not Eclipse.
hi,
why we give radiobutton.htm at the end of the url . instead of that , if we give anything it shows 404 error page not found. i understand the dispatcher servelet concept and it maps the url pattern ends with the .htm . still my doubt is on why we give radiobutton.htm. are we mapped anywhere in controller?
Hi mkyong, I have created radiobutton and defaulted it then the value is getting set and it is working smooth but when i select the value on the UI manually the value is not getting set i.e. its not getting printed on the next screen or so.
Please help me on above mentioned query..thanks in advance.