Spring MVC Read checkbox values from Java model





Hey guys in this post, you will learn about reading checkbox values from Java model class with easy to understand example.

Read More:

Overview


  • In Spring MVC is represented by the tag <form:checkbox />
  • If you want to read radio button values from java model then we can use <form:checkboxes />
<form:checkboxes path="departments" items="${employee.departmentOptions}" />

Complete Example


Lets create a step by step maven project to understand the Spring MVC

Create a maven project


First you need to create a maven webapp project. You can check the below post to create new maven webapp project –

  • Create a maven webapp project

Add Maven Dependencies


Open pom.xml and add the following maven dependencies

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>in.bushansirgur</groupId>
	<artifactId>springmvc</artifactId>
	<packaging>war</packaging>
	<version>1.0.0</version>
	<name>springmvc Maven Webapp</name>
	<url>http://maven.apache.org</url>
	<properties>
		<maven.compiler.source>1.11</maven.compiler.source>
		<maven.compiler.target>1.11</maven.compiler.target>
		<spring.version>4.3.6.RELEASE</spring.version>
		<failOnMissingWebXml>false</failOnMissingWebXml>
	</properties>
	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
		    <groupId>javax.servlet</groupId>
		    <artifactId>jsp-api</artifactId>
		    <version>2.0</version>
		    <scope>provided</scope>
		</dependency>
		<dependency>
		    <groupId>jstl</groupId>
		    <artifactId>jstl</artifactId>
		    <version>1.2</version>
		</dependency>
	</dependencies>
	<build>
		<finalName>springmvc</finalName>
	</build>
</project>

Configure Spring MVC App


Create AppConfig.java class inside in.bushansirgur.springmvc.config package and add the following content

package in.bushansirgur.springmvc.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "in.bushansirgur.springmvc")
public class AppConfig {
	
	//define the bean for view resolver
	@Bean
	public ViewResolver viewResolver() {
		InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
		viewResolver.setPrefix("/WEB-INF/view/");
		viewResolver.setSuffix(".jsp");
		return viewResolver;
	}
}

Configure Dispatcher Servlet


Create MySpringMvcDispatcherServletInitializer.java inside in.bushansirgur.springmvc.config package and add the following content




package in.bushansirgur.springmvc.config;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class MySpringMvcDispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

	@Override
	protected Class<?>[] getRootConfigClasses() {
		return null;
	}

	@Override
	protected Class<?>[] getServletConfigClasses() {
		return new Class[] {AppConfig.class};
	}

	@Override
	protected String[] getServletMappings() {
		return new String[] {"/"};
	}

}

Create a Java model


Inside src/main/java create a package in.bushansirgur.springmvc.model, under this create Employee.java and add the following content


package in.bushansirgur.springmvc.model;

import java.util.LinkedHashMap;

public class Employee {
	
	private String firstName;
	
	private String lastName;
	
	private String country;
	
	private LinkedHashMap<String, String> countryOptions;

	private LinkedHashMap<String, String> genderOptions;
	
	private LinkedHashMap<String, String> departmentOptions;
	
	private String gender;
	
	private String[] departments;
	
	public Employee() {
		//populate country options
		countryOptions = new LinkedHashMap<String, String>();
		countryOptions.put("IND", "India");
		countryOptions.put("AUS", "Australia");
		countryOptions.put("GER", "Germany");
		countryOptions.put("CAN", "Canada");
		countryOptions.put("SAF", "South Africa");
		
		//populate gender options
		genderOptions = new LinkedHashMap<String, String>();
		genderOptions.put("Male", "Male");
		genderOptions.put("Female", "Female");
		
		//populate department options
		departmentOptions = new LinkedHashMap<String, String>();
		departmentOptions.put("Sales", "Sales");
		departmentOptions.put("Marketing", "Marketing");
		departmentOptions.put("HR", "HR");
		departmentOptions.put("Admin", "Admin");
		departmentOptions.put("IT", "IT");
	}
	
	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	public String getCountry() {
		return country;
	}

	public void setCountry(String country) {
		this.country = country;
	}

	public LinkedHashMap<String, String> getCountryOptions() {
		return countryOptions;
	}

	public void setCountryOptions(LinkedHashMap<String, String> countryOptions) {
		this.countryOptions = countryOptions;
	}

	public String getGender() {
		return gender;
	}

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

	public LinkedHashMap<String, String> getGenderOptions() {
		return genderOptions;
	}

	public void setGenderOptions(LinkedHashMap<String, String> genderOptions) {
		this.genderOptions = genderOptions;
	}

	public String[] getDepartments() {
		return departments;
	}

	public void setDepartments(String[] departments) {
		this.departments = departments;
	}

	public LinkedHashMap<String, String> getDepartmentOptions() {
		return departmentOptions;
	}

	public void setDepartmentOptions(LinkedHashMap<String, String> departmentOptions) {
		this.departmentOptions = departmentOptions;
	}
	
}

Create a Controller


Inside src/main/java create a package in.bushansirgur.springmvc.controller, under this create HomeController.java and add the following content

package in.bushansirgur.springmvc.controller;

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 in.bushansirgur.springmvc.model.Employee;

@Controller
public class HomeController {
	
	@RequestMapping(value = "/")
	public String showHomePage(Model theModel) {
		theModel.addAttribute("employee", new Employee());
		return "home-page";
	}
	
	@RequestMapping(value = "/processForm")
	public String showDashboardPage(@ModelAttribute("employee") Employee theEmployee, Model theModel) {
		theModel.addAttribute("employee", theEmployee);
		return "dashboard";
	}
}

@ModelAttribute annotation will bind the form values to the Java object.

Create a view template


Create home-page.jsp inside webapp/WEB-INF/view folder and add the following content

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
	<h1>Read the textbox value</h1>
	<hr/>
	<form:form action="processForm" modelAttribute="employee">
		First Name:<form:input path="firstName" /><br/><br/>
		Last Name: <form:input path="lastName" /><br/><br/>
		Country: <form:select path="country">
			<form:options items="${employee.countryOptions}" />
		</form:select>
		<br/><br/>
		Gender: 
		<form:radiobuttons path="gender" items="${employee.genderOptions}" />
		<br/><br/>
		Departments:
		<form:checkboxes items="${employee.departmentOptions}" path="departments"/>
		<br/><br/>
		<button type="submit">Submit</button>
	</form:form>
</body>
</html>

model attribute in the <form:form> tag takes the name of the model which we added to the Model object in handler method.

Create dashboard.jsp inside webapp/WEB-INF/view folder and add the following content

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
	<h1>Read the textbox value</h1>
	<hr/>
	<p>Employee First name: ${employee.firstName}</p>
	<p>Employee Last name: ${employee.lastName}</p>
	<p>Employee country: ${employee.country}</p>
	<p>Employee Gender: ${employee.gender}</p>
	<p>Employee Department: </p>
	<ul>
		<c:forEach var="department" items="${employee.departments}">
			<li>${department}</li>
		</c:forEach>
	</ul>
</body>
</html>

Run the App


Start the tomcat server, navigate to the URL localhost:8080/springmvc/
01

02

That’s it for this post, if you like this post, share this with your friends and colleagues or you can share this within your social media platform. Thanks, I will see you in our next post.



Bushan Sirgur

Hey guys, I am Bushan Sirgur from Banglore, India. Currently, I am working as an Associate project in an IT company.

Leave a Reply