Spring MVC Form Validation Example
Validation and Submission of a form is an important aspect of a web application. In this tutorial, we will show how to validate the form fields of a simple login form using the Spring MVC framework.
1. Spring MVC Form Validation – Introduction
1.1 Spring Framework
- Spring is an open-source framework created to address the complexity of an enterprise application development
- One of the chief advantages of the Spring framework is its layered architecture, which allows a developer to be selective about which of its components they can use while providing a cohesive framework for
J2EE
application development - Spring framework provides support and integration to various technologies for e.g.:
- Support for Transaction Management
- Support for interaction with the different databases
- Integration with the Object Relationship frameworks for e.g. Hibernate, iBatis etc
- Support for Dependency Injection which means all the required dependencies will be resolved with the help of containers
- Support for
REST
style web-services
1.2 Spring Mvc Framework
Model-View-Controller (Mvc) is a well-known design pattern for designing the GUI based applications. It mainly decouples the business logic from UI by separating the roles of Model, View, and Controller in an application. This pattern divides the application into three components to separate the internal representation of the information from the way it is being presented to the user. The three components are:
- Model (M): Model’s responsibility is to manage the application’s data, business logic, and the business rules. It is a
POJO
class which encapsulates the application data given by the controller - View (V): A view is an output representation of the information, such as displaying information or reports to the user either as a text-form or as charts. Views are usually the
JSP
templates written with Java Standard Tag Library (JSTL
) - Controller (C): Controller’s responsibility is to invoke the Models to perform the business logic and then update the view based on the model’s output. In the spring framework, the controller part is played by the Dispatcher Servlet
Now, open up the Eclipse IDE and let’s see how to implement the form validation functionality in the spring mvc framework!
2. Spring MVC Form Validation Example
Here is a step-by-step guide for implementing this tutorial in the spring mvc framework.
2.1 Tools Used
We are using Eclipse Kepler SR2, JDK 8 and Maven. Having said that, we have tested the code against JDK 1.7 and it works well.
2.2 Project Structure
Firstly, let’s review the final project structure, in case you are confused about where you should create the corresponding files or folder later!
2.3 Project Creation
This section will demonstrate how to create a Java-based Maven project with Eclipse. In Eclipse IDE, go to File -> New -> Maven Project
.
In the New Maven Project window, it will ask you to select project location. By default, ‘Use default workspace location’ will be selected. Just click on next button to proceed.
Select the Maven Web App archetype from the list of options and click next.
It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT
.
Click on Finish and the creation of a maven project is completed. If you observe, it has downloaded the maven dependencies and a pom.xml
file will be created. It will have the following code:
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/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.spring.mvc</groupId> <artifactId>SpringMvcFormValidation</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> </project>
We can start adding the dependencies that developers want like Servlet API, Spring Mvc etc. Let’s start building the application!
3. Application Building
Below are the steps involved in developing this application.
3.1 Maven Dependencies
Here, we specify the dependencies for the spring mvc framework and the bean validation api (a.k.a hibernate-validator-<version_number>.Final.jar
). The rest dependencies such as Spring Beans, Spring Core, Validation API etc. will be automatically resolved by Maven. The updated file will have the following code:
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.spring.mvc</groupId> <artifactId>SpringMvcFormValidation</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>SpringMvcFormValidation Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <!-- Servlet API Dependency --> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>3.0-alpha-1</version> </dependency> <!-- Spring Framework Dependencies --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.0.6.RELEASE</version> </dependency> <!-- jar is used for showing the server side validations in the spring framework --> <dependency> <groupId>org.hibernate.validator</groupId> <artifactId>hibernate-validator</artifactId> <version>6.0.10.Final</version> </dependency> </dependencies> <build> <finalName>SpringMvcFormValidation</finalName> </build> </project>
3.2 Configuration Files
Let’s write all the configuration files involved in this application.
3.2.1 Web Deployment Descriptor
The web.xml
file declares one servlet (i.e. Dispatcher Servlet) to receive all kind of the requests. Dispatcher servlet here acts as a front controller. Add the following code to it:
web.xml
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> <display-name>SpringMvcFormValidationExample</display-name> <servlet> <servlet-name>springmvcformvalidationdispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>springmvcformvalidationdispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
3.2.2 Spring Configuration File
To configure the spring framework, developers need to implement a bean configuration file i.e. springmvcformvalidationdispatcher-servlet.xml
which provide an interface between the basic Java class and the outside world. Add the following code to it:
springmvcformvalidationdispatcher-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"> <mvc:annotation-driven /> <context:component-scan base-package="com.spring.mvc.demo" /> <context:component-scan base-package="com.spring.mvc.demo.pojo" /> <context:annotation-config /> <!-- For reading the properties files --> <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> <property name="basename" value="/WEB-INF/message" /> </bean> <!-- For resolving the view name and invoking the particular view page for the user --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/" /> <property name="suffix" value=".jsp" /> </bean> </beans>
Do note:
- This file is loaded by the spring’s Dispatcher Servlet which receives all the requests coming into the application and dispatches them to the controller for processing
- This file has the
ReloadableResourceBundleMessageSource
bean declaration that tells the spring framework to localize the validation error messages for the login form fields. Here,- The
basename
property is a mandatory attribute that provides the location of the resource bundles
- The
- This file has the
InternalResourceViewResolver
bean declaration that tells the framework how to find the physicalJSP
files according to the logical view names returned by the controllers, by attaching the prefix and the suffix to a view name
3.3 Message Resource File
We will create a properties file which will contain the validation error message for the login form fields. Create the message.properties
file in the SpringMvcFormValidation/src/main/webapp/WEB-INF
folder and add the following code to it:
message.properties
## userform.email ## NotEmpty.userform.email=Please enter your e-mail. Email.userform.email=Your e-mail is incorrect. ## userform.password ## Size.userform.password=Your password must between 6 and 10 characters.
3.4 Java Class Creation
Let’s write the Java classes involved in this application.
3.4.1 Model Class
Let’s create a simple model class. In this class, the member variables are annotated with the validation constraint annotations such as: @NotEmpty
, @Email
, @Size
. Do note, the error messages are specified in the properties file for demonstrating the localization of the validation error messages. Add the following code to it:
User.java
package com.spring.mvc.demo.pojo; import javax.validation.constraints.Email; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.Size; import org.springframework.stereotype.Component; @Component public class User { @NotEmpty @Email private String email; @Size(min=6, max=10, message="Size.userform.password") private String password; public User() { } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
3.4.2 Controller Class
Let’s create a simple class where the @Controller
annotation specifies this class as a spring controller and is responsible for handling the incoming requests. In here, the model object is annotated with the @Valid
annotation that binds the model object properties with the inputs from the JSP form that uses the spring’s form tags. Any constraints violations will be exported as errors in the BindingResult
object. Add the following code to it:
FormCtrl.java
package com.spring.mvc.demo; import javax.validation.Valid; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.spring.mvc.demo.pojo.User; @Controller public class FormCtrl { @RequestMapping(value= "/init", method= RequestMethod.GET) public String initView(Model model) { model.addAttribute("userform", new User()); return "loginForm"; } @RequestMapping(value= "/login", method= RequestMethod.POST) public String doLogin(@Valid @ModelAttribute("userform") User user, BindingResult result) { if (result.hasErrors()) { return "loginForm"; } return "success"; } }
3.5 JSP View
Spring Mvc supports many types of views for different presentation technologies. These include – JSP
, HTML
, XML
etc. So let us write a simple result view in SpringMvcFormValidation/src/main/webapp/WEB-INF/views
folder.
3.5.1 Input Form Page
This is the login form page of the tutorial which takes the user input and displays the appropriate error messages in case of the validation errors. Add the following code to it:
loginForm.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> <%@ page isELIgnored="false" %> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Login</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <link rel="stylesheet" href="https://examples.javacodegeeks.com/wp-content/litespeed/localres/aHR0cHM6Ly9tYXhjZG4uYm9vdHN0cmFwY2RuLmNvbS8=bootstrap/4.1.3/css/bootstrap.min.css"> <style type="text/css"> .errormsg { color: red; } </style> </head> <body> <div class="container"> <h2 align="center" class="text-primary">Spring MVC Form Validation Example</h2> <hr /> <div> </div> <form:form action="/SpringMvcFormValidation/login" method="POST" modelAttribute="userform"> <div class="form-group"> <label>Email:</label><form:input path="email" size="30" cssClass="form-control" placeholder="Enter email" /> <small><form:errors path="email" cssClass="errormsg" /></small> </div> <div class="form-group"> <label>Password:</label><form:password path="password" size="30" cssClass="form-control" placeholder="Enter password" /> <small><form:errors path="password" cssClass="errormsg" /></small> </div> <div class="form-group"> <button type="submit" class="btn btn-primary">Validate</button> </div> </form:form> </div> </body> </html>
3.5.2 Output Page
The success page will be displayed in case the user enters a valid email address and password. Add the following code to it:
success.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> <%@ page isELIgnored="false" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Welcome</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <link rel="stylesheet" href="https://examples.javacodegeeks.com/wp-content/litespeed/localres/aHR0cHM6Ly9tYXhjZG4uYm9vdHN0cmFwY2RuLmNvbS8=bootstrap/4.1.3/css/bootstrap.min.css"> </head> <body> <div class="container"> <h2 align="center" class="text-primary">Spring MVC Form Validation Example</h2> <hr /> <div> </div> <h4 align="center">Welcome <span class="text-success">${userform.email}</span>! You're successfully logged in.</h4> </div> </body> </html>
4. Run the Application
As we are ready with all the changes, let us compile the project and deploy the application on the Tomcat7 server. To deploy the application on Tomat7, right-click on the project and navigate to Run as -> Run on Server
.
Tomcat will deploy the application in its web-apps folder and shall start its execution to deploy the project so that we can go ahead and test it on the browser.
5. Project Demo
Open your favorite browser and hit the following URL to display the application’s login form page.
http://localhost:8082/SpringMvcFormValidation/
Server name (localhost) and port (8082) may vary as per your tomcat configuration.
Try to enter an invalid email address and a short password (e.g. 4 characters), and click the Validate
button. Users will see the validation error messages in red, as shown below.
Now enter a valid email address and a valid password (between 6 and 10 characters), and click the Validate
button. The login success page appears.
That’s all for this tutorial and I hope the article served you whatever you were looking for. Happy Learning and don’t forget to share!
6. Conclusion
In this section, developers learned how to implement form validation in the spring mvc framework. Developers can download the sample application as an Eclipse project in the Downloads section.
7. Download the Eclipse Project
This was an example of Spring MVC Form Validation.
You can download the full source code of this example here: SpringMvcFormValidation
After creating this app I got HTTP status404(Requested resource not found)
How to resolve this.
Did you downloaded the source code or build it from scratch. I downloaded the source code and it ran fine.
Really helpful .It runs beautifully. Thanks a lot and keep up the good work
Thank you, Ankit! Happy new year! :)
if i run this program it is nt displaying anything
i downloaded your projct nd in index.jsp it includes only this
<%
request.getRequestDispatcher(“/init”).forward(request, response);
%>
I dnt know where to paste it ..kindly help