Wednesday, October 16, 2024

Spring MVC Radiobutton And Radiobuttons Form Tag Example

In this post we’ll see how to use radiobutton and radiobuttons tag provided by the form tag library in the Spring MVC framework.

Spring MVC Project structure using Maven


<form:radiobutton> and <form:radiobuttons> tags in Spring MVC

  • <form:radiobutton>- This tag renders an HTML 'input' tag with type 'radio'. With this tag the values for the radio button are hardcoded with in the JSP page. You will have multiple radiobutton tag instances bound to the same property but with different values.
  • <form:radiobuttons>- If you don't want to harcode the values for the radiobutton in the JSP but want to pass available options at runtime then you can use radiobuttons tag.

In this post we’ll see example using both <form:radiobutton> and <form:radiobuttons> one by one.

Spring MVC radiobutton example

For the Spring MVC form radiobutton tag example let’s assume there is a class UserPreferences that stores the radio button value. There are two set of radiobuttons in the JSP and there are two properties in the UserPreferences bean class to store the selected option.

Spring MVC radiobutton example – Model Class

public class UserPreferences {
	private String exercise;
	private String gender;
	
	public String getExercise() {
		return exercise;
	}
	public void setExercise(String exercise) {
		this.exercise = exercise;
	}
	public String getGender() {
		return gender;
	}
	public void setGender(String gender) {
		this.gender = gender;
	}
}

Spring MVC radiobutton example – View

There is a JSP (user.jsp) that has two sets of radiobutton tag with options for user to select.

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
  <title>Spring MVC tutorial - User</title>
</head>
<body>
<h3>Spring MVC radio button example</h3>
  <form:form method="POST" action="showPreferences" modelAttribute="preferences">
    <table>
      <tr>
        <td><b>Gender:</b></td>
        <td>
          <form:radiobutton path="gender" value="M"/>Male
          <form:radiobutton path="gender" value="F"/>Female
          <form:radiobutton path="gender" value="O"/>Other
        </td>
      </tr>
      <tr>
        <td><b>Favorite Exercise:</b></td>
        <td>
          <form:radiobutton path="exercise" value="Aerobic"/>Aerobic
          <form:radiobutton path="exercise" value="Anaerobic"/>Anaerobic
          <form:radiobutton path="exercise" value="Flexibility Trng"/>Flexibility Training
        </td>
      </tr>
      <tr>
        <td><input type="submit" value="Submit"></td>
      </tr>
    </table>
  </form:form>
</body>
</html>

The values for the properties are taken from an object of type UserPreferences bean which is bound using the attribute “modelAttribute” with in the form tag. The object is set with in the handler method of the Controller class.

There is another JSP that is used to display the selected radio button option.

showPreferences.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>User Preferences</title>
</head>
<body>
  <h3>Spring MVC radio button example</h3>
  Gender: ${preferences.gender}<br/>
  Favorite exercise: ${preferences.exercise}
</body>
</html>

Spring MVC radiobutton example – Controller class

import org.netjs.model.UserPreferences;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class UserController {
	@RequestMapping(value = "/user", method = RequestMethod.GET)
	public String showUser(Model model) throws Exception{
    UserPreferences pref = new UserPreferences();    
    // Setting default values
    pref.setGender("M");
    pref.setExercise("Anaerobic");
    model.addAttribute("preferences", pref);
    return "user";
	}
	    
	@RequestMapping(value = "/showPreferences", method = RequestMethod.POST)
	public String showPreferences(@ModelAttribute("preferences") UserPreferences preferences, Model model) throws Exception{
    model.addAttribute("preferences", preferences);
    return "showPreferences";
	}
}

In the Controller class, showUser() method is used to handle the /showUser request path. Method returns the view name as "user" which resolves to /WEB-INF/jsp/user.jsp JSP.

In the handler method object of UserPreferences class is set to the Model which is used in the JSP to bind the bean properties with the radio button. If you want any radio button option to be selected by default in JSP then you can set the values for the properties in the UserPreferences object.

Another handler method showPreferences() handles the request when submit button is clicked in the user.jsp.

Deploying and testing the application

Once the application is deployed to Tomcat server it can be accessed using the URL- http://localhost:8080/springwebproj/user (As per the web application name used in this example, please change as per your web application)

Spring MVC radiobutton tag

Page which shows the selected options.

Spring form tag library radiobutton tag

Spring MVC radiobuttons tag example

If you want to provide the options for the radiobutton at runtime rather than hardcoding them then you can use radiobuttons tag in Spring MVC application. You pass in an Array, a List or a Map containing the available options in the "items" property.

Spring MVC radiobuttons tag example – Model Class

public class UserPreferences {

	private String exercise;
	private String gender;
	
	public String getExercise() {
		return exercise;
	}
	public void setExercise(String exercise) {
		this.exercise = exercise;
	}
	public String getGender() {
		return gender;
	}
	public void setGender(String gender) {
		this.gender = gender;
	}
}

Spring MVC radiobuttons example – Views

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
  <title>Spring MVC tutorial - User</title>
</head>
<body>
<h3>Spring MVC radio button example</h3>
  <form:form method="POST" action="showPreferences" modelAttribute="preferences">
    <table>
      <tr>
        <td><b>Gender:</b></td>
        <td><form:radiobuttons path="gender" items="${genderOptions}"/></td>
      </tr>
      <tr>
        <td><b>Favorite Exercise:</b></td>
        <td><form:radiobuttons path="exercise" items="${exerciseList}"/></td>
      </tr>
      <tr>
        <td><input type="submit" value="Submit"></td>
      </tr>
    </table>
  </form:form>
</body>
</html>

As you can see now <form:radiobuttons> tag is used with the items property. The values used with the items property in the JSP genderOptions and exerciseList should be available as a model attribute containing String of values to be selected from. If a Map is used, the map entry key will be used as the value and the map entry’s value will be used as the label to be displayed.

There is another JSP that is used to display the selected radio button option.

showPreferences.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>User Preferences</title>
</head>
<body>
  <h3>Spring MVC radio button example</h3>
  Gender: ${preferences.gender}<br/>
  Favorite exercise: ${preferences.exercise}
</body>
</html>

Spring MVC radiobuttons example – Controller class

@Controller
public class UserController {
    
  @RequestMapping(value = "/user", method = RequestMethod.GET)
  public String showUser(Model model) throws Exception{
    UserPreferences pref = new UserPreferences();    
    // Default Values
    pref.setGender("F");
    pref.setExercise("Flexibility Trng");
    
    // Preparing values for "Sex Options" radio button
    Map<String, String> genderOptions = new HashMap<>();
    genderOptions.put("M", "Male");
    genderOptions.put("F", "Female");
    genderOptions.put("O", "Other");
    model.addAttribute("genderOptions", genderOptions);
    model.addAttribute("preferences", pref);
    return "user";
  }

  @RequestMapping(value = "/showPreferences", method = RequestMethod.POST)
  public String showPreferences(@ModelAttribute("preferences") UserPreferences preferences, Model model) throws Exception{
    model.addAttribute("preferences", preferences);
    return "showPreferences";
  }
      
  // List for "Favorite Exercise" radio button
  @ModelAttribute("exerciseList")
  public List<String> getExerciseList(){
    List<String> exerciseList = new ArrayList<>();
    exerciseList.add("Aerobic");
    exerciseList.add("Anaerobic");
    exerciseList.add("Flexibility Trng");
    return exerciseList;
  }
}

As you can see exerciseList and genderOptions which are used in the JSP to show radiobutton options are set here as model attribute. Default values for the radio buttons are also set here to be pre-selected.

Deploying and testing the application

Once the application is deployed to Tomcat server it can be accessed using the URL- http://localhost:8080/springwebproj/user

Reference- https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc-view-jsp-formtaglib

That's all for this topic Spring MVC Radiobutton And Radiobuttons Form Tag Example. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Spring Tutorial Page


Related Topics

  1. Spring MVC Checkbox And Checkboxes Form Tag Example
  2. Spring MVC Example With @PathVaribale - Creating Dynamic URL
  3. Spring MVC Exception Handling Example Using @ExceptionHandler And @ControllerAdvice
  4. Spring MVC Excel Generation Example
  5. Spring Batch Processing Using JDBCTemplate batchUpdate() Method

You may also like-

  1. registerShutdownHook() Method in Spring Framework
  2. Bean Definition Inheritance in Spring
  3. Excluding Bean From Autowiring in Spring
  4. Using Conditional Annotation in Spring Framework
  5. How LinkedList Class Works Internally in Java
  6. Difference Between CountDownLatch And CyclicBarrier in Java
  7. BigDecimal in Java
  8. Converting double to int - Java Program

No comments:

Post a Comment