How to perform Form Validation with Spring Boot

We have ever known that JavaScript can validate a Form on Client side, and this tutorial helps you to perform Form Validation on Server side.

Related article: How to create Custom Validation in Spring

I. Technology

– Java 1.8
– Maven 3.3.9
– Spring Tool Suite – Version 3.8.1.RELEASE
– Spring Boot: 1.5.1.RELEASE

II. Overview
1. Project Structure


WebController is a Controller which has request mapping methods to display our page.
RequestInfo is a Data Model Class with annotation for validation.
webapp folder contains all necessary JSP file and static resource.
application.properties contains settings for prefix and suffix for JSP files.
Dependencies for Spring Boot, Tomcat Embed Jasper and Hibernate Validator in pom.xml.

2. Step to do

– Create Spring Boot project & add Dependencies
– Create jsp file and static resource
– Set prefix and suffix resolution
– Create Data Model Class
– Create Web Controller
– Run Spring Boot Application & Enjoy Result

III. Practice
1. Create Spring Boot project & add Dependencies

Open Spring Tool Suite, on Menu, choose File -> New -> Spring Starter Project, then fill each fields. Remember that we will the Packaging is War.

Click Next, then click Finish.

Open pom.xml and add Dependencies:

Note: (for another case)
If you create a Spring Starter Project with Jar Packaging, you should change

to

Then, extends @SpringBootApplication Class with SpringBootServletInitializer and add the code below:

2. Create jsp file and static resource

– Under src/main/webapp folder, create new folder named WEB-INF and jsps inside, then create:
request.jsp

successful.jsp

– Next, create main.css in webapp/css:

3. Set prefix and suffix resolution

Under src/main/resources, open application.properties and add:

We have another way to set prefix and suffix, just follow the steps below:
– add dependency to pom.xml:

– then create a Bean:

4. Create Data Model Class

Under package model, create RequestInfo class with @Email and @Size(…) annotation for validating fields inside the class:

5. Create Web Controller

Under package controller, create WebController class:

@Valid annotation indicates that the Model should be validated.
@ModelAttribute(“requestInfo”) specifies the object that form will work with. It matches modelattribute in HTML or JSP file:

6. Run Spring Boot Application & Enjoy Result

– Config maven build:
clean install
– Run project with mode Spring Boot App
– Check results:

Case 1:

Case 2:

Press Submit, the site will come to:

In Console Window, the System generates the String:

IV. Source Code

SpringFormValidation


Related Posts



Got Something To Say:

Your email address will not be published. Required fields are marked *

*