Open In App

Spring – MVC Form Checkbox

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will learn about the Spring MVC Checkbox and Checkboxes tags. We will create a basic Spring MVC project in the Spring tool suite(STS) to create checkboxes using form:checkbox and form:checkboxes tags.

‘spring-form.tld’ tag library

In Spring Framework, we can use Java Server Pages (JSPs) as a view component. To implement views using JSP, Spring Framework provides a form tag library namely spring-form.tld with some tags for evaluating errors, setting themes, formatting the fields for inputting and outputting internationalized messages.

‘checkbox’ tag: The ‘checkbox’ is one of the tag provided by the spring-form.tld library. It renders an HTML ‘input’ tag with type ‘checkbox’.

HTML




<form:checkbox path=" " value=" " />


‘checkboxes’ tag: The ‘checkbox’ is one of the tag provided by the spring-form.tld library. It renders multiple HTML ‘input’ tags with type ‘checkbox’.

HTML




<form:checkboxes path=" " items=" " />


Spring MVC Application

We will be creating the below Spring MVC application,

Spring MVC – Checkbox Example

Steps to Create an Application

  1. Create a Spring MVC project in Spring Tool Suite.
  2. In STS, while creating the project based on the developer selection, it will download all the required maven dependencies, *.jar, lib files and it will provide an embedded server.
  3. Below is the final project structure of the Spring MVC project after creating *.java and *.jsp files also.

Project Structure

Implementation: Files to be created are as follows:

  1. Home.java – Bean class – To define the properties and getter/setter methods of the properties.
  2. HomeController.java – Controller class – To process the user request and generate the output.
  3. home.jsp – Jsp file to interact with the user for the input.
  4. summary.jsp – Jsp file to display the output after processing to the user.

A. File: home.jsp

HTML




<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Home page</title>
</head>
<body>
  
    <h1>Welcome to GeeksforGeeks!</h1>
  
    <form:form action="submit" method="post" modelAttribute="home">
        <table>
            <tr>
                <td><form:label path="name">Enter your name: </form:label></td>
                <td><form:input path="name" /></td>
            </tr>
            <tr>
                <td><form:label path="duration">Select duration of course: </form:label></td>
                <td><form:checkbox path="duration" value="3 months" label="3 Months"/> 
                    <form:checkbox path="duration" value="6 months" label="6 Months" disabled="true"/></td>
            </tr>
            <tr>
                <td><form:label path="framework">Java Frameworks: </form:label></td>
                <td><form:checkboxes path="framework" items="${javaFramworks}" delimiter="|"/></td>
            </tr>
            <tr>
                <td><form:button>Submit</form:button></td>
            </tr>
        </table>
    </form:form>
  
</body>
</html>


Output explanation: 

This is the home page displayed to the user when the application starts. To use Spring form tags, first, we need to include the taglib URI – “http://www.springframework.org/tags/form” in the Jsp page. In the form tag – action, method attributes are used to map the controller method that has to be executed when the page submits. The checkbox tag has many attributes like path, cssStyle, dir, value, etc. We can include any number of attributes based on our requirements.

In this example, we have included the below attributes,

  1. path – To specify the path to the property that needs to be bound with the data. Here, the data-bind to duration property in checkbox and framework property in checkboxes tags.
  2. value – To specify the value to the particular checkbox.
  3. label – To display the name of the value for the checkbox.
  4. disabled – It is a boolean attribute to make the checkbox disabled when the value is true. By default, the value will be false.
  5. items – To display the checkboxes names from the list.
  6. delimiter – To specify a delimiter to use between each ‘input’ tag with type ‘checkbox’. Here we are using ‘|’ symbol as a delimiter.

B. Home.java

Java




// Java Program to Illustrate Home Class 
  
package com.geek.app;
  
// Class
public class Home {
  
    // Class data members
    public String name;
    public String duration;
    public String framework;
  
    // Getter
    public String getName() { return name; }
  
    // Setter
    public void setName(String name) { this.name = name; }
  
    // Getter
    public String getDuration() { return duration; }
  
    // Setter
    public void setDuration(String duration)
    {
        this.duration = duration;
    }
  
    // Getter
    public String getFramework() { return framework; }
  
    // Setter
    public void setFramework(String framework)
    {
        this.framework = framework;
    }
}


  • This is the java bean class to define the required parameters.
  • Here, we are defining name, duration, and framework as parameters and their getter/setter methods to get/set the values to the properties.

C. HomeController.java

Java




// Java Program to Illustrate HomeController Class
  
package com.geek.app;
  
// importing required classes
import java.util.Arrays;
import java.util.List;
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;
  
// Annotation
@Controller
  
// Class
public class HomeController {
  
    // Annotation
    @RequestMapping(value = "/")
  
    public String viewHome(Model model)
    {
  
        // Creating an instance of Home class
        // inside this method
        Home home = new Home();
        model.addAttribute("home", home);
  
        return "home";
    }
  
    // Annotation
    @ModelAttribute("javaFramworks")
  
    // Method
    public List<String> javaFramworksList()
    {
        List<String> framework = Arrays.asList(
            "Apache Struts", "Spring", "Hibernate",
            "Grails", "Java Server Faces");
  
        return framework;
    }
  
    // Annotation
    @RequestMapping(value = "/submit",
                    method = RequestMethod.POST)
  
    // Method
    public String
    submit(@ModelAttribute("home") Home home)
    {
  
        return "summary";
    }
}


Output Explanation: This is the controller class where it executes the methods based on the mapping of the request URLs. Here, @Controller, conveys to the container that this class is the spring controller class. To use this annotation we need to import org.springframework.stereotype.Controller package. 

The annotation, @RequestMapping, maps the request URL’s to the specified method based on the value provided. o use this annotation, we need to import org.springframework.web.bind.annotation.RequestMapping package. The annotation @ModelAttribute, used to bind a method parameter or method return value to the named model attribute. We need to import org.springframework.web.bind.annotation.ModelAttribute package. The RequestMethod specifies the type of the request whether it is a get request or post request.

D. File: summary.jsp

HTML




<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Summary page</title>
</head>
<body>
  
    <h3>Hello ${home.name}!!</h3>
  
    <span>Course Duration: </span>
    <span>${home.duration}</span>
    <br>
    <span>Frameworks Selected: </span>
    <span>${home.framework}</span>
  
</body>
</html>


  • This is the output Jsp page to display the user entered values in the browser after the processing of the request.

Execution

  • After creating all the required .java and .jsp files, run the project on the server.
  • Right on the Project, Run as -> Run on Server.
  • Select the server in the localhost to run the application.
  • Open the URL: http://localhost:8080/app/ in the browser to get the below screen.

Home Page – home.jsp

As we specified,

  • disabled=true for 6 Months checkbox, it is showing disabled in the screen.
  • delimiter = |, the specified delimiter is displaying between the checkbox names.

Now, select the checkbox values and click on submit button.

Selection of the input

  • Once the page is submitted, we will get the below output with the details we have selected.

Output – summary.jsp



Last Updated : 24 Feb, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads