Flat Preloader Icon

Spring MVC Form Radio Button

  • In a Spring MVC application, you can create radio buttons in a form using the tag from the Spring Form Tag Library. Radio buttons allow users to select one option from a set of choices. Here’s how to create radio buttons in a Spring MVC form:
  • Assuming you have a form backing bean (a model) with a field for radio button choices, you can create radio buttons as follows:

Include the Spring Form Tag Library:

  • Make sure to include the Spring Form Tag Library at the top of your JSP file where you want to create the form:
				
					<%@ taglib prefix="form"
uri="http://www
.springframework.org/tags/form" %>

				
			

Create the Form:

  • Use the tag to create the form, specifying the model attribute to which the form data should be bound:
				
					<form:form modelAttribute="myForm"
method="POST" action
="/processForm">
    <!-- Radio Buttons -->
    <label>Select Gender:</label>
    <form:radiobutton path="gender" 
    value="MALE" />
    Male
    <form:radiobutton path="gender"
    value="FEMALE" /> 
    Female
    <form:radiobutton path="gender" 
    value="OTHER" />
    Other
    <br>
    <input type="submit" value="Submit" />
</form:form>

				
			
  • In this example:
    • modelAttribute=”myForm” specifies that the form data should be bound to a model attribute named myForm.
    • form:radiobutton tags generate HTML radio buttons for the gender field of the myForm model. The path attribute specifies the field to bind to, and the value attribute specifies the value associated with each radio button choice.
    • The form submits data to the /processForm URL using the HTTP POST method when the “Submit” button is clicked.

Controller Method:

  • In your Spring MVC controller, create a method to handle the form submission. This method should map to the action URL specified in the form.
				
					@Controller
public class MyController {

    @GetMapping("/showForm")
    public String showForm(Model model) {
        model.addAttribute
        ("myForm", new MyForm()); 
        
return "my-form-page"; // The view name
    }

    @PostMapping("/processForm")
    public String processForm
    (@ModelAttribute("myForm") 
    MyForm myForm) {
    // Process form data
    (e.g., save it to a database)
        return "confirmation-page"; 
        
    }
}

				
			

Form Backing Bean (Model):

  • Ensure you have a form backing bean (in this case, MyForm) with a field named gender, along with getter and setter methods for that field.
				
					public class MyForm {
    private String gender;


    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }
}