MVC

Spring MVC Form Handling Example

Photo of Theodora FragkouliTheodora FragkouliJuly 31st, 2014Last Updated: February 19th, 2019
1 246 10 minutes read

With this tutorial we shall explain create and submit a form in Spring MVC. Spring MVC provides tags that are data binding-aware and allow us to handle form elements, compining JSP and Spring Web MVC. Each tag in Spring MVC provides support for the set of attributes of its corresponding HTML tag, thus making the tags familiar and intuitive to use.

In this example we shall make use of atextbox, apassword, acheckbox, adropdown box and ahidden value, all tags provided by Spring MVC. They will be used as properties inside a class, which is the MVC model. There is also a validator for all these fields, and a view that contains a form with all these fields to fill and submit.
 
 

Tip
You may skip project creation and jump directly to thebeginning of the example below.

Our preferred development environment isEclipse. We are using Eclipse Juno (4.2) version, along withMaven Integration plugin version 3.1.0. You can download Eclipse fromhere and Maven Plugin for Eclipse fromhere. The installation of Maven plugin for Eclipse is out of the scope of this tutorial and will not be discussed. We are also using JDK 7_u_21.Tomcat 7 is the application server used.

Let’s begin,

1. Create a new Maven project

Go to File -> Project ->Maven -> Maven Project.

New Maven Project
New Maven Project – step 1

In the “Select project name and location” page of the wizard, make sure that “Create a simple project (skip archetype selection)” option isunchecked, hit “Next” to continue with default values.

New Maven project
New Maven project- step 2

Here the maven archetype for creating a web application must be added. Click on“Add Archetype” and add the archetype. Set the “Archetype Group Id” variable to"org.apache.maven.archetypes", the “Archetype artifact Id” variable to"maven-archetype-webapp" and the “Archetype Version” to"1.0". Click on“OK” to continue.

maven-archetype-webapp
Add Maven archetype

In the “Enter an artifact id” page of the wizard, you can define the name and main package of your project. Set the “Group Id” variable to"com.javacodegeeks.snippets.enterprise" and the “Artifact Id” variable to"springexample". The aforementioned selections compose the main project package as"com.javacodegeeks.snippets.enterprise.springexample" and the project name as"springexample". Set the “Package” variable to"war", so that a war file will be created to be deployed to tomcat server. Hit “Finish” to exit the wizard and to create your project.

Configure Maven project
Configure Maven project

The Maven project structure is shown below:

New project structure
New project structure

    It consists of the following folders:

  • /src/main/java folder, that contains source files for the dynamic content of the application,
  • /src/test/java folder contains all source files for unit tests,
  • /src/main/resources folder contains configurations files,
  • /target folder contains the compiled and packaged deliverables,
  • /src/main/resources/webapp/WEB-INF folder contains the deployment descriptors for the Web application ,
  • the pom.xml is the project object model (POM) file. The single file that contains all project related configuration.

2. Add Spring-MVC dependencies

Add the dependencies in Maven’spom.xml file, by editing it at the “Pom.xml” page of the POM editor. The dependency needed for MVC is thespring-webmvc package. Thejavax.validation and thehibernate-validator packages will be also used here for validation:

pom.xml

<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>com.javacodegeeks.snippets.enterprise</groupId><artifactId>springexample</artifactId><packaging>war</packaging><version>0.0.1-SNAPSHOT</version><name>springexample Maven Webapp</name><url>http://maven.apache.org</url><dependencies><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>${spring.version}</version></dependency><dependency><groupId>javax.servlet</groupId><artifactId>servlet-api</artifactId><version>2.5</version></dependency><dependency>            <groupId>javax.validation</groupId>            <artifactId>validation-api</artifactId>            <version>1.1.0.Final</version>        </dependency>        <dependency>            <groupId>org.hibernate</groupId>            <artifactId>hibernate-validator</artifactId>            <version>5.1.0.Final</version>        </dependency></dependencies><build><finalName>springexample</finalName></build><properties><spring.version>3.2.9.RELEASE</spring.version></properties></project>

3. Create the model

Form.java is the class that will be used as the model. It has properties for all the fields that will be used in the form, which are atextbox, apassword, acheckbox, adropdown box and ahidden value. All fields must have getters and setters to be rendered in the view.

Form.java

package com.javacodegeeks.snippets.enterprise.form.model;import java.util.List;public class Form {//  textbox, password,//  checkbox, dropdown, hidden valueprivate String name;private String email;private String gender;private String password;private String passwordConf;private List<String> courses;private String tutor;private String hiddenMessage;public String getName() {return name;}public void setName(String name) {this.name = name;}public String getEmail() {return email;}public void setEmail(String email) {this.email = email;}public String getGender() {return gender;}public void setGender(String gender) {this.gender = gender;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public String getPasswordConf() {return passwordConf;}public void setPasswordConf(String passwordConf) {this.passwordConf = passwordConf;}public List<String> getCourses() {return courses;}public void setCourses(List<String> courses) {this.courses = courses;}public String getTutor() {return tutor;}public void setTutor(String tutor) {this.tutor = tutor;}public String getHiddenMessage() {return hiddenMessage;}public void setHiddenMessage(String hiddenMessage) {this.hiddenMessage = hiddenMessage;}}

4. Create a Validator

The validator is the class that will be used in the controller to check on the values of each field in the form. In order to create a validator class, we are making use of the API provided by Spring MVC.FormValidator.java below implements theorg.springframework.validation.Validator, and overrides the two methods it provides.

Theboolean supports(Class<?> paramClass) method is used to check if the validator can validate instances of theparamClass.

In thevalidate(Object obj, Errors errors) method, an instance of the class is provided, and anErrors object. Theorg.springframework.validation.ValidationUtils is used here, since it offers validation API methods to check the fields of the object. All error messages are passed in theerror object. Aproperties file with error messages is used here to pass various validation messages to theerrors object as shown below:

FormValidator.java

package com.javacodegeeks.snippets.enterprise.form.validator;import java.util.List;import org.springframework.validation.Errors;import org.springframework.validation.ValidationUtils;import org.springframework.validation.Validator;import com.javacodegeeks.snippets.enterprise.form.model.Form;public class FormValidator implements Validator {private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})

quot;;

public boolean supports(Class<?> paramClass) {
return Form.class.equals(paramClass);
}

public void validate(Object obj, Errors errors) {
Form form = (Form) obj;
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "valid.name");
if(!form.getEmail().matches(EMAIL_PATTERN)) {
errors.rejectValue("email","valid.email");
}
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "gender", "valid.gender");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "valid.password");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "passwordConf", "valid.passwordConf");
if (!form.getPassword().equals(form.getPasswordConf())) {
errors.rejectValue("passwordConf", "valid.passwordConfDiff");
}
List<String> courses = form.getCourses();
if (courses == null || courses.size() < 2) {
errors.rejectValue("courses", "valid.courses");
}
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "tutor", "valid.tutor");
}
}
Thevalidation.properties file below is the file that contains all the error messages.

validation.properties

valid.name= Please type your namevalid.gender = Please select your gender!valid.email=Please type a correct emailvalid.password=Please select a passwordvalid.passwordConf=Please confirm your passwordvalid.passwordConfDiff=Your password is differentvalid.courses = Please select at least two courses!valid.tutor=Please choose your tutor!

5. Create the Controller

TheController is where theDispatcherServlet will delegate requests. The@Controller annotation indicates that the class serves the role of a Controller. The@RequestMapping annotation is used to map a URL to either an entire class or a particular handler method.

Aorg.springframework.validation.Validator is injected here, via the@Autowired annotation, also making use of the@Qualifier annotation to specify that theFormValidator.java implementation of theorg.springframework.validation.Validator class is injected.

The@InitBinder annotation ininitBinder(WebDataBinder binder) method allows us to configure web data binding directly within the controller. With@InitBinder we can initialize theWebDataBinder, that is used for data binding from web request parameters to JavaBean objects. Here, theWebDataBinder is where the validator is set.

The Controller consists of two basic methods, a GET method, which isString initForm(Model model) and a POST method, which isString submitForm(Model model, @Validated Form form, BindingResult result). The first method creates and returns to the"form" view a new instance of theForm.java class. The second method also gets theModel, and theForm object created in the form.Form is annotated with the@Validated annotation, which allows the form object to be validated with the validator.BindingResult is where all validation errors are automatically passed, so it can be used to decide the next navigation step. If there are no errors, the validation is successful, so the method returns the String representation of thesuccessForm.jsp page, and the form object is passed at theModel. Otherwise, the returned String is the String representation of theform.jsp page, which also has the error messages, as will be shown below.

Theprivate void initModelList(Model model) method is used to initialize all lists that are passed to the model for the tags that use options, such as thecheckbox and thedropdown box. So every time the form is rendered these lists are not null. If the lists are not initialized, then the iteration over the items of the lists leads to aNullPointerException.

FormController.java

package com.javacodegeeks.snippets.enterprise.form;import java.util.ArrayList;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Qualifier;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.validation.BindingResult;import org.springframework.validation.Validator;import org.springframework.validation.annotation.Validated;import org.springframework.web.bind.WebDataBinder;import org.springframework.web.bind.annotation.InitBinder;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import com.javacodegeeks.snippets.enterprise.form.model.Form;@Controller@RequestMapping("/form.htm")public class FormController {    @Autowired    @Qualifier("formValidator")    private Validator validator;        @InitBinder    private void initBinder(WebDataBinder binder) {        binder.setValidator(validator);    }@RequestMapping(method = RequestMethod.GET)public String initForm(Model model) {Form form = new Form();form.setHiddenMessage("JavaCodeGeek");model.addAttribute("form", form);initModelList(model);return "form";}@RequestMapping(method = RequestMethod.POST)public String submitForm(Model model, @Validated Form form, BindingResult result) {model.addAttribute("form", form);String returnVal = "successForm";if(result.hasErrors()) {initModelList(model);returnVal = "form";} else {model.addAttribute("form", form);}return returnVal;}private void initModelList(Model model) {List<String> courses = new ArrayList<String>();courses.add("Maths");courses.add("Physics");courses.add("Geometry");courses.add("Algebra");courses.add("Painting");model.addAttribute("courses", courses);List<String> genders = new ArrayList<String>();genders.add("Male");genders.add("Female");model.addAttribute("genders", genders);List<String> tutors = new ArrayList<String>();tutors.add("Mrs Smith");tutors.add("Mr Johnson");tutors.add("Mr Clarks");model.addAttribute("tutors", tutors);model.addAttribute("genders", genders);}}

6. Create the view with a form

The view below is a simple example of how to create a form. It is a simple html view consisting of thehead andbody html tags.

Want to master Spring Framework ?
Subscribe to our newsletter and download theSpring Framework Cookbookright now!
In order to help you master the leading and innovative Java framework, we have compiled a kick-ass guide with all its major features and use cases! Besides studying them online you may download the eBook in PDF format!

Thank you!

We will contact you soon.

In order to create a form in Spring MVC, we make use of theform:form tag. Itsmethod property is set to POST, and thecommandName property is set to the name of the backing bean that is binded to the Model, which is theForm.java class.

Theform:input tag is used to create the textbox, with itspath property set to the field binded to it. Theform:password tag is used to create the password field. Theform:checkboxes tag has another property to configure, appart from thepath property. It also provides theitems property, where the list of the items to be displayed is set.

In order to create ahidden value, we are using the simpleinput tag, withname property set to thehiddenMessage, which is the field bound to it. Its type parameter is set tohidden, so this component is not visible in the view. It also has avalue parameter set to a String message.

Theform:errors tag defines where the error message of the specified field will be displayed in the view. Finally, theinput tag, withtype property set tosubmit is used for the submit button.

form.jsp

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%><html><head><title>Spring MVC form submission</title></head><body><h2>Fill your form!</h2><form:form method="POST" commandName="form"><table><tr><td>Enter your name:</td><td><form:input path="name" /></td><td><form:errors path="name" cssStyle="color: #ff0000;"/></td></tr><tr><td>Enter your mail:</td><td><form:input path="email" /></td><td><form:errors path="email" cssStyle="color: #ff0000;" /></td></tr><tr><td>Enter your gender</td><td><form:checkboxes path="gender" items="${genders}" /></td><td><form:errors path="gender" cssStyle="color: #ff0000;"/></td> </tr><tr><td>Enter a password:</td><td><form:password path="password"  showPassword="true"/></td><td><form:errors path="password" cssStyle="color: #ff0000;"/></td><tr><td>Confirm your password:</td><td><form:password path="passwordConf" showPassword="true"/></td><td><form:errors path="passwordConf" cssStyle="color: #ff0000;"/></td></tr><tr><td>Choose the courses you like:</td><td><form:checkboxes path="courses" items="${courses}" /></td><td><form:errors path="courses" cssStyle="color: #ff0000;"/></td> </tr><tr><td>Please select your tutor:</td><td><form:select path="tutor">  <form:option value="" label="...." />  <form:options items="${tutors}" />       </form:select>                </td><td><form:errors path="tutor" cssStyle="color: #ff0000;" /></td></tr><tr><form:hidden path="hiddenMessage"/></tr><tr><td><input type="submit" name="submit" value="Submit"></td></tr><tr></table></form:form></body></html>

Below is the page that will be rendered when the validation of the form succeeds:

successForm.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%><%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%><html><head><title>Spring MVC form submission</title></head><body>Dear ${form.name}, <br>Your mail is ${form.email}<br>You chose the courses below:<br><c:forEach var="course" items="${form.courses}">  <c:out value="${course}"/><br></c:forEach><br>${form.tutor} will be your tutor!<br>Your hidden nickname is ${form.hiddenMessage}</body></html>

7. Configure the application

The files that we must configure in the application are theweb.xml file and themvc-dispatcher-servlet.xml file.

Theweb.xml file is the file that defines everything about the application that a server needs to know. It is placed in the/WEB-INF/ directory of the application. The<servlet> element declares theDispatcherServlet. When theDispatcherServlet is initialized, the framework will try to load the application context from a file named[servlet-name]-servlet.xml located in/WEB-INF/ directory. So, we have created themvc-dispatcher-servlet.xml file, that will be explained below. The<servlet-mapping> element ofweb.xml file specifies what URLs will be handled by theDispatcherServlet.

web.xml

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <display-name>Archetype Created Web Application</display-name> <servlet><servlet-name>mvc-dispatcher</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet        </servlet-class><load-on-startup>1</load-on-startup></servlet> <servlet-mapping><servlet-name>mvc-dispatcher</servlet-name><url-pattern>/</url-pattern></servlet-mapping> </web-app>

 
Themvc-dispatcher-servlet.xml file is also placed inWebContent/WEB-INF directory. Theorg.springframework.web.servlet.view.InternalResourceViewResolver bean is used as internal resource views resolver, meaning that it will find thejsp andhtml files in theWebContent/WEB-INF/ folder. We can also set properties such asprefix orsuffix to the view name to generate the final view page URL. This is the file where all beans created, such as Controllers are placed and defined.

The<context:component-scan> tag is used, so that the Spring container will search for all annotated classes under thecom.javacodegeeks.snippets.enterprise package. The<mvc:annotation-driven> tag is used, so that the container searches for annotated classes, to resolve MVC. TheFormValidator.java class is also defined here as a bean, with an id.

Finally, theResourceBundleMessageSource is used, to provide access to resource bundles using specified basenames. Itsbasename property is set tovalidation, thus pointing to the properties file that holds the validation messages.

mvc-dispatcher-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">  <context:component-scan base-package="com.javacodegeeks.snippets.enterprise" />  <mvc:annotation-driven /><beanclass="org.springframework.context.support.ResourceBundleMessageSource"><property name="basename" value="validation" /></bean> <bean />    <beanclass="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="prefix"><value>/WEB-INF/</value></property><property name="suffix"><value>.jsp</value></property></bean></beans>

8. Run the application

Now, let's run the application. We first build the project with Maven. All we have to do is right click on the project and select ->Run As: Maven build. The goal must be set to package. The.war file produced must be placed inwebapps folder of tomcat. Then, we can start the server.

Hit on:

http://localhost:8080/springexample/form.htm

initial form
initial form

So, here is our form. Press the submit button before having entered any values:

validation error messages
validation error messages

As a result all validation messages are rendered. Now, press different passwords and a wrong email and press the submit button again:

more validation error messages
more validation error messages

Again, there are validation messages. Now complete your form correctly and press on submit button:

form submitted
form submitted

There you go, your form is correctly submitted!

9. Download the Eclipse Project

This was an example of how handle a form in Spring MVC.

Download
You can download the full source code of this example here:SpringMVCFormHandling
Do you want to know how to develop your skillset to become aJava Rockstar?
Subscribe to our newsletter to start Rockingright now!
To get you started we give you our best selling eBooks forFREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to theTerms andPrivacy Policy

Thank you!

We will contact you soon.

Photo of Theodora FragkouliTheodora FragkouliJuly 31st, 2014Last Updated: February 19th, 2019
1 246 10 minutes read
Photo of Theodora Fragkouli

Theodora Fragkouli

Theodora has graduated from Computer Engineering and Informatics Department in the University of Patras. She also holds a Master degree in Economics from the National and Technical University of Athens. During her studies she has been involved with a large number of projects ranging from programming and software engineering to telecommunications, hardware design and analysis. She works as a junior Software Engineer in the telecommunications sector where she is mainly involved with projects based on Java and Big Data technologies.
Subscribe
Notify of
guest
I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.

I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.