Spring MVC Tutorial

Core Spring MVC

Spring MVC - Annotation

Spring MVC - Form Handling

Spring MVC with JSTL

Spring MVC with REST API

Spring MVC with Database

Spring MVC - Form Radio Button

Using radio buttons in a Spring MVC form is a common requirement, and Spring's Form tag library simplifies the process. Let's walk through creating and processing radio buttons using Spring MVC.

1. Model:

Consider we have a User model and we want the user to select their gender:

public class User {
    private String gender;

    // Getters and setters...
}

2. Controller:

Populate a list or a map of radio button choices and add it to the model:

@Controller
public class UserController {

    @ModelAttribute("genderList")
    public Map<String, String> getGenderList() {
        Map<String, String> genderList = new LinkedHashMap<>();
        genderList.put("M", "Male");
        genderList.put("F", "Female");
        return genderList;
    }

    @GetMapping("/register")
    public String showForm(Model model) {
        model.addAttribute("user", new User());
        return "registerForm";
    }

    @PostMapping("/register")
    public String submitForm(@ModelAttribute User user, Model model) {
        // Process the form...
        model.addAttribute("user", user);
        return "registrationResult";
    }
}

Here, the getGenderList method annotated with @ModelAttribute will automatically add the gender list to the model for the view.

3. JSP View:

In your JSP (registerForm.jsp), use the form:radiobuttons tag:

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>

<form:form method="POST" modelAttribute="user">
    <!-- Other form fields -->

    Gender: <form:radiobuttons path="gender" items="${genderList}" />

    <input type="submit" value="Register" />
</form:form>

Here, the items attribute of form:radiobuttons is populated with the genderList map, and the selected radio button will set the corresponding value to the gender attribute of the User model.

4. Displaying the Result:

You can display the selected gender in your result view (registrationResult.jsp):

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<h1>Registration Details:</h1>
<p>Gender: <c:out value="${user.gender}" /></p>

The value will be M or F, depending on the user's selection. You can use conditional rendering to display "Male" or "Female" based on the value.

That's it! You've successfully integrated radio buttons into a Spring MVC form. Remember to always validate user inputs and handle any errors gracefully for a better user experience.

  1. Spring MVC Form Radio Button Example:

    • Description: This is a basic example illustrating the use of radio buttons in a Spring MVC form. It typically involves creating a form with radio button inputs and processing the form data on the server.

    • Code Snippet: (HTML Form with Radio Buttons)

      <!-- radioForm.jsp -->
      <form action="/submitForm" method="post">
          <label><input type="radio" name="gender" value="male"> Male</label>
          <label><input type="radio" name="gender" value="female"> Female</label>
          <button type="submit">Submit</button>
      </form>
      
  2. Handling Radio Buttons in Spring MVC Forms:

    • Description: This example expands on the basic radio button example by providing a Spring MVC controller method to handle the submitted form data.

    • Code Snippet: (Controller Method)

      @Controller
      public class FormController {
          @PostMapping("/submitForm")
          public String processForm(@RequestParam("gender") String gender) {
              // Process radio button value
              return "formResult";
          }
      }
      
  3. Radio Button Binding in Spring MVC:

    • Description: This example demonstrates how to use data binding to bind the selected radio button value directly to a model attribute in Spring MVC.

    • Code Snippet: (Model Attribute and Controller Method)

      public class UserForm {
          private String gender;
      
          // Getter and Setter
      }
      
      @Controller
      public class BindingController {
          @PostMapping("/submitForm")
          public String submitForm(@ModelAttribute("userForm") UserForm userForm) {
              // Access userForm.getGender() for radio button value
              return "formResult";
          }
      }
      
  4. Populating Radio Buttons in Spring MVC:

    • Description: This example involves dynamically populating the options of radio buttons in a Spring MVC form.

    • Code Snippet: (Controller Method with Model Attribute)

      @Controller
      public class RadioButtonsController {
          @ModelAttribute("genders")
          public List<String> populateGenders() {
              // Logic to fetch dynamic genders from a data source
              return Arrays.asList("Male", "Female", "Other");
          }
      
          @GetMapping("/showForm")
          public String showForm(Model model) {
              model.addAttribute("userForm", new UserForm());
              return "radioForm";
          }
      
          @PostMapping("/submitForm")
          public String submitForm(@ModelAttribute("userForm") UserForm userForm) {
              // Access userForm.getGender() for selected gender value
              return "formResult";
          }
      }
      
  5. Spring MVC Radio Button Validation:

    • Description: This example includes validation for the radio button value in the Spring MVC form.

    • Code Snippet: (Model Attribute with Validation)

      public class UserForm {
          @NotBlank(message = "Please select a gender")
          private String gender;
      
          // Getter and Setter
      }
      
  6. Radio Button with Thymeleaf in Spring MVC:

    • Description: This example demonstrates how to use Thymeleaf to render and handle radio buttons in a Spring MVC application.

    • Code Snippet: (Thymeleaf Radio Buttons)

      <!-- radioForm.html -->
      <form action="/submitForm" method="post" th:object="${userForm}">
          <label th:each="gender : ${genders}">
              <input type="radio" th:id="${gender}" th:name="gender" th:value="${gender}" th:checked="${gender == userForm.gender}" />
              <span th:text="${gender}"></span>
          </label>
          <button type="submit">Submit</button>
      </form>
      
  7. Dynamic Radio Buttons in Spring MVC:

    • Description: This example goes a step further by dynamically updating the options of radio buttons based on user interactions.

    • Code Snippet: (Controller Method with Dynamic Options)

      @Controller
      public class DynamicRadioButtonsController {
          @GetMapping("/getDynamicGenders")
          @ResponseBody
          public List<String> getDynamicGenders(@RequestParam("category") String category) {
              // Logic to fetch dynamic genders based on the selected category
              return Arrays.asList("Male", "Female", "Other");
          }
      }
      
  8. Spring MVC Radio Button Group:

    • Description: This example shows how to use a radio button group to enforce the selection of one option from a group.

    • Code Snippet: (HTML Form with Radio Button Group)

      <!-- radioGroupForm.jsp -->
      <form action="/submitForm" method="post">
          <label><input type="radio" name="group" value="option1"> Option 1</label>
          <label><input type="radio" name="group" value="option2"> Option 2</label>
          <label><input type="radio" name="group" value="option3"> Option 3</label>
          <button type="submit">Submit</button>
      </form>
      
  9. Selecting Default Value in Spring MVC Radio Button:

    • Description: This example shows how to pre-select a default value for a radio button in a Spring MVC form.

    • Code Snippet: (Pre-selected Radio Button)

      <!-- Pre-selected radio button -->
      <form action="/submitForm" method="post">
          <label><input type="radio" name="gender" value="male" checked> Male</label>
          <label><input type="radio" name="gender" value="female"> Female</label>
          <button type="submit">Submit</button>
      </form>
      
  10. Processing Radio Button Values in Spring MVC Controller:

    • Description: This example includes a Spring MVC controller method that processes the submitted form data, including the selected radio button value.

    • Code Snippet: (Controller Method)

      @Controller
      public class FormController {
          @PostMapping("/submitForm")
          public String processForm(@RequestParam("gender") String gender) {
              // Process selected radio button value
              return "formResult";
          }
      }