Spring MVC Form Checkbox

Spring MVC provides several form tags used to develop web applications (Usually JSP pages). One of them is a checkbox tag. The checkbox tag offers us to choose multiple options at the same time.

Below is given a code snippet which shows how to use the <form:checkbox> tag:

 Dancing <form:checkbox path = "hobbies" value = "Dancing" />
 Singing <form:checkbox path = "hobbies" value = "Singing" /> 

The <form:checkbox> tag is used to create an HTML checkbox field in which the values are hard-coded inside the JSP pages, whereas the <form:checkboxes> tag is used to create multiple checkboxes in which the checkbox values are generated at run time. The <fom:checkboxes> tag is only used when we don’t want to list down the elements in the JSP page.

Below is given a code snippet, which shows how to use the <form:checkboxes> tag:

<form:checkboxes path =
"hobbies" items = "${student.list}" />  

Example of MVC Form Checkbox

Here, we are going to create an example of <form:checkbox>.


Following are the steps to create an example of <form:checkbox> tag:

  • Create a request page

In this step, we are going to create a request page named index.jsp.

index.jsp

 <html>
 <body>
 <h2> Spring MVC Web application </h2>
 <a href = "student_form"> Student Form </a>
 </body>
 </html> 
  •  Create the Model class which stores data

In this step, we are going to create a Model class named Student.java, which stores the checkbox values.

Student.java

 import java.util.LinkedHashMap;
 public class Student {
             private String fname;
             private String lname;
             private String country;
             private LinkedHashMap<String, String> countryoptions;
             private String planguage;
             private String[] hobbies;
             public Student() {
               countryoptions = new LinkedHashMap<String, String>();
                         countryoptions.put("IND","India");
                         countryoptions.put("FRA","France");
                         countryoptions.put("USA","America");
                         countryoptions.put("DUB","Dubai");
                         countryoptions.put("NEP", "Nepal");
                         countryoptions.put("BHU", "Bhutan");
                         countryoptions.put("UK", "United Kingdom");
             }
             public String getCountry() {
                         return country;
             }
             public LinkedHashMap<String, String> getCountryoptions() {
                         return countryoptions;
             }
             public void setCountry(String country) {
                         this.country = country;
             }
             public String getFname() {
                         return fname;
             }
             public void setFname(String fname) {
                         this.fname = fname;
             }
             public String getLname() {
                         return lname;
             }
             public void setLname(String lname) {
                         this.lname = lname;
             }
             public String getPlanguage() {
                         return planguage;
             }
             public void setPlanguage(String planguage) {
                         this.planguage = planguage;
             }
             public String[] getHobbies() {
                         return hobbies;
             }
             public void setHobbies(String[] hobbies) {
                         this.hobbies = hobbies;
             }
  } 
  • Create the Controller class

In this step, we are going to create a Controller named StudentController.java.

StudentController.java

 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.RequestParam;
 @Controller
 public class StudentController {
             @RequestMapping("/student_form")
             public String showStudentForm( Model m) {
                         Student student = new Student();
                         m.addAttribute("student", student);
                         return "studentform" ;
             }
             @RequestMapping("/studentregis")
             public String showStudentData(@ModelAttribute("student") Student student) {
                         return "student-data" ;
             }
  } 
  • Add the entry of Controller in the web.xml

In this step, we are going to add the entry of the Controller inside the web.xml.

web.xml

 <?xml version = "1.0" encoding = "UTF-8"?>
 <web-app xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
             xmlns = "http://xmlns.jcp.org/xml/ns/javaee"
             xsi:schemaLocation = "http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
             id = "WebApp_ID" version = "3.1">
             <display-name>spring-mvc-demo</display-name>
             <absolute-ordering />
             <!-- Spring MVC Configs -->
             <!-- Step 1: Configure Spring MVC Dispatcher Servlet -->
             <servlet>
                         <servlet-name>dispatcher</servlet-name>
                         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
                         <init-param>
                                     <param-name>contextConfigLocation</param-name>
                                     <param-value>/WEB-INF/spring-servlet.xml</param-value>
                         </init-param>
                         <load-on-startup>1</load-on-startup>
             </servlet>
             <!-- Step 2: Set up URL mapping for Spring MVC Dispatcher Servlet -->
             <servlet-mapping>
                         <servlet-name>dispatcher</servlet-name>
                         <url-pattern>/</url-pattern>
             </servlet-mapping>
 </web-app> 
  • Define the Model class in another XML file

In this step, we are going to define the bean in another XML file (spring-servlet.xml).

spring-servlet.xml

 <?xml version = "1.0" encoding = "UTF-8"?>
 <beans xmlns = "http://www.springframework.org/schema/beans"
             xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" 
             xmlns:context = "http://www.springframework.org/schema/context"
             xmlns:mvc = "http://www.springframework.org/schema/mvc"
             xsi:schemaLocation = "  http://www.springframework.org/schema/beans
             http://www.springframework.org/schema/beans/spring-beans.xsd
             http://www.springframework.org/schema/context
             http://www.springframework.org/schema/context/spring-context.xsd
             http://www.springframework.org/schema/mvc
         http://www.springframework.org/schema/mvc/spring-mvc.xsd"> 
             <!-- Step 3: Add support for component scanning -->
             <context:component-scan base-package = "com.app.SpringMVCFormTag"  />
             <!-- Step 4: Add support for conversion, formatting and validation support -->
             <mvc:annotation-driven/>
             <!-- Step 5: Define Spring MVC view resolver -->
             <bean
                         class="org.springframework.web.servlet.view.InternalResourceViewResolver">
                         <property name = "prefix" value = "/WEB-INF/view/" />
                         <property name = "suffix" value = ".jsp" />
             </bean>
 </beans> 
  • Create all the view pages

In this step, we are going to create the other view pages (JSP pages).

studentform.jsp

 <%@ taglib prefix = "form" uri = "http://www.springframework.org/tags/form" %>  
 <html>
 <head>
 <title>Student Registration Form
 </title>
 </head>
 <body>
 <form:form action = "studentregis" modelAttribute = "student" >
 FIRST NAME: <form:input path = "fname" />
 <br></br>
 LAST NAME: <form:input path = "lname" />
 <br></br>
 COUNTRY: <form:select path="country">
    <form:options items = "${student.countryoptions}"></form:options>
 </form:select>
 <br></br>
 PROGRAMMING LANGUAGE:
 <br></br>
 Java <form:radiobutton path = "planguage" value = "Java" />
 Python <form:radiobutton path = "planguage" value = "Python" />
 C++ <form:radiobutton path = "planguage" value = "C++" />
 PHP <form:radiobutton path = "planguage" value = "PHP" />
 <br></br>
 HOBBIES:
 <br></br>
 Dancing <form:checkbox path = "hobbies" value = "Dancing" />
 Singing <form:checkbox path = "hobbies" value = "Singing" />
 Travelling <form:checkbox path = "hobbies" value = "Travelling"/>
 Reading <form:checkbox path = "hobbies" value = "Reading" />
 <br></br>
 <input type = "submit" value = "Submit"/>
 </form:form>
 </body>
 </html> 

student-data.jsp

 <%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>
 <!DOCTYPE html>
 <html>
 <head>
 <title>Student Registration Data</title>
 </head>
 <body>
 The student name is ${student.fname} ${student.lname}
 <br></br>
 Country: ${student.country}
 <br></br>
 Programming Language: ${student.planguage}
 <br></br>
 Hobbies:
 <ul>
    <c:forEach var = "temp" items ="${student.hobbies}">
        <li> ${temp} </li>
    </c:forEach>
 </ul>
 </body>
 </html> 

Output

Spring MVC Form Checkbox
Spring MVC Form Checkbox 1
Spring MVC Form Checkbox 2
Spring MVC Form Checkbox 3

Related Topics

Spring – Bean Lifecycle

Spring – Bean Lifecycle Spring bean is responsible for managing the lifecycle of beans created by the Spring container.  The lifecycle of the bean is easy to understand. When a bean is created, it requires...

4 minutes read.

Spring Autowiring – Constructor Injection

Spring Autowiring – Constructor Injection We have previously discussed an example of Constructor Dependency Injection (CDI) using an XML-based configuration. In the previous case, we have defined the reference of the constructor in...

2 minutes read.

Spring AOP – @After Advice

Spring AOP – @After Advice We have previously discussed the concepts of Spring AOP. One of the AOP concepts is Advice, which is further divided into various types. After (finally) is a type of advice...

3 minutes read.

Spring Framework Annotations

Spring Framework Annotations Spring framework provides a variety of annotations for a better approach. Using annotations, we can develop Spring applications (small & large scale) easily with less code. Following are the annotations...

6 minutes read.

Spring Tutorial

What is Spring Framework? Spring is one of the most popular enterprise application framework used for developing Java applications. “Spring is a lightweight open-source framework. It allows Java developer to build simple, reliable,...

6 minutes read.

Spring MVC Example

Spring MVC Example We have previously discussed the Spring Web MVC framework. In this tutorial, we are going to create a simple example of Spring Web MVC. Following are the steps used to create an example...

2 minutes read.

Spring – Beans using @Bean

Spring – Beans using @Bean We have previously discussed an example of Spring configuration using an XML-based configuration. In the previous example, we have defined beans inside the bean-configuration file (applicationContext.xml). To make the...

3 minutes read.

Spring AOP – @Before Advice Type

Spring AOP – @Before Advice Type As we have discussed, AOP (Aspect-Oriented Programming) is one of the powerful features of the Spring framework. It complements the Object-Oriented Programming (OOPs). AOP provides some concepts and terminology,...

2 minutes read.

Spring MVC Form Tag Library

The Spring MVC provides a variety of tags available in the form of a tag library, which is used to develop web pages (JSP view pages). The Spring’s form tag...

6 minutes read.

Spring – Configuration using @Configuration

Spring – Configuration using @Configuration We have previously discussed the Spring configuration using an XML configuration file. In that case, we have defined all the bean information in the bean-configuration file (applicationContext.xml). ...

3 minutes read.

Spring - Bean Scope

Spring - Bean Scope Bean Scope refers to a lifecycle of the bean. It allows us to have control over the creation of bean objects. It is a very powerful approach and provides...

6 minutes read.

Spring MVC – @RequestParam

We have already discussed an example of Spring MVC in our previous tutorials. Here, we are going to discuss the @RequestParam annotation. In the last case, we had created a bean class for...

8 minutes read.

Spring MVC Form – Radio Button

A variety of form tags are available in Spring MVC for developing web applications, <form:radiobutton> tag is one of them. The radio button tag is used to choose only one option among a...

10 minutes read.

Spring AOP – @AfterReturning Advice

Spring AOP – @AfterReturning Advice We have discussed earlier the types of advices available in Spring AOP. One of them is After Returning advice. It is an advice that executes after the normal execution...

3 minutes read.

Spring Model Interface

Model Interface Model is an interface that defines a holder for model attributes. It is also used to transfer data between various parts of the Spring MVC application. The Model interface is available...

8 minutes read.

Spring MVC Number Range Validation

Example of Number Range Validation Here, we are going to create an example of number range validation. Following are the steps to create an example of number range validation. Create a request page In this step, we are...

12 minutes read.

Spring Autowiring

Spring Autowiring Autowiring is an essential feature of the Spring framework. The autowiring function is used for wiring beans automatically, without injecting the beans using <constructor-arg> and <property> elements in the bean-config file. It can...

3 minutes read.

Spring MVC Tutorial

Spring MVC is a web Model-View-Controller framework built on Servlet API. It is used to build web applications. The MVC framework works around central servlet called DispatcherServlet. It dispatches the requests to the...

4 minutes read.

Spring – Dependency Injection

Spring – Dependency Injection One of the main features of Inversion of Control (IoC) is Dependency Injection (DI). It is a process of supplying the dependencies from one object to others. The Spring-Core container...

8 minutes read.

Spring MVC Regular Expression Validation

Example of Regular Expression Validation Here, we are going to create an example of regular expression validation. Following are the steps to create an example of a regular expression: Create a request page In this step, we are going...

13 minutes read.