Spring MVC Form Validation (With Annotations)

This post provides a simple example of a HTML form validation. It is based on the Spring MVC With Annotations example. The code is available on GitHub in the Spring-MVC-Form-Validation directory.
 
 
 
 
 
 
 
 

Data

For this example we will use a bean and JSR303 validation annotations:

public class MyUser {

    @NotNull
    @Size(min=1,max=20)
    private String name;

    @Min(0)
    @Max(120)
    private int age;

    public MyUser(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public MyUser() {
        name = '';
        age = 0;
    }

    // Setters & Getters

}

Pages

Our form will contain input elements, but also the possibility to display error messages:

<%@page contentType='text/html' pageEncoding='UTF-8'%>
<%@ taglib prefix='form' uri='http://www.springframework.org/tags/form' %>
<!doctype html>
<html>
<head>
  <meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>
  <title>My User Form!</title>
</head>
<body>
  <form:form method='post' action='myForm' commandName='myUser'>
    <table>
      <tr>
        <td>Name: <font color='red'><form:errors path='name' /></font></td>
      </tr>
      <tr>
        <td><form:input path='name' /></td>
      </tr>
      <tr>
        <td>Age: <font color='red'><form:errors path='age' /></font></td>
      </tr>
      <tr>
        <td><form:input path='age' /></td>
      </tr>
      <tr>
        <td><input type='submit' value='Submit' /></td>
      </tr>
    </table>
  </form:form>
</body>
</html>

Our success page is:

<%@page contentType='text/html' pageEncoding='UTF-8'%>
<%@taglib prefix='form' uri='http://www.springframework.org/tags/form'%>
<%@ taglib prefix='c' uri='http://java.sun.com/jsp/jstl/core' %>
<!doctype html>
<html>
<head>
  <meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>
  <title>Form Processed Successfully!</title>
</head>
<body>
    Form processed for <c:out value='${myUser.name}' /> ! <br />
    <a href='<c:url value='/'/>'>Home</a>
</body>
</html>

Our home page:

<%@page contentType='text/html' pageEncoding='UTF-8'%>
<%@ taglib prefix='c' uri='http://java.sun.com/jsp/jstl/core' %>
<!doctype html>
<html lang='en'>
<head>
  <meta charset='utf-8'>
  <title>Welcome !!!</title>
</head>
<body>
  <h1>
    Spring Form Validation !!!
  </h1>
<a href='<c:url value='/myForm'/>'>Go to the form!</a>
</body>
</html>

Controller

Notice that we need to use @ModelAttribute to make sure an instance of MyUser is always available in the model. In the validateForm(), we need to use @ModelAttribute to move the content of the form to the MyUser project.

@Controller
public class MyController {

    @RequestMapping(value = '/')
    public String home() {
        return 'index';
    }

    @ModelAttribute('myUser')
    public MyUser getLoginForm() {
        return new MyUser();
    }

    @RequestMapping(value = '/myForm', method = RequestMethod.GET)
    public String showForm(Map model) {
        return 'myForm';
    }

    @RequestMapping(value = '/myForm', method = RequestMethod.POST)
    public String validateForm(
        @ModelAttribute('myUser') @Valid MyUser myUser,
        BindingResult result, Map model) {

        if (result.hasErrors()) {
            return 'myForm';
        }

        model.put('myUser', myUser);

        return 'success';

    }

}

Maven Dependencies

We need the following dependencies. The Hibernate validator dependency is necessary to process JSR303 annotations:

<dependency>
  <groupId>javax.validation</groupId>
  <artifactId>validation-api</artifactId>
  <version>1.0.0.GA</version>
  <type>jar</type>
</dependency>

<dependency>
  <groupId>org.hibernate</groupId>
  <artifactId>hibernate-validator</artifactId>
  <version>4.3.0.Final</version>
</dependency>

Running The Example

Once compiled, the example can be run with
mvn tomcat:run. Then, browse:


http://localhost:8383//spring-mvc-form-validation/.

If the end user enters invalid values, error messages will be displayed:


 

Reference: Spring MVC Form Validation (With Annotations) from our JCG partner Jerome Versrynge at the Technical Notes blog.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

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 ....

3 Responses to "Spring MVC Form Validation (With Annotations)"

  1. Steve Hanson says:

    Nice post. Thanks for sharing!

  2. Vamsi Kancharla says:

    Here is a sample github code that demonstrates input form validation using JSON services, rather than JSP for the view. The tutorial also demonstrates validation against XSS and injections.

    https://github.com/vam-si/javaee7-springmvc

  3. Ernesto says:

    Hi, I have a big question. Is it possible send a list or array of objects for to be validated with “hasErros”?
    By Example, I have a object called “calification”, this object contains 2 attributes: “cal” and “decimal”. In my JSP I send a list of alumns, for each of then I want to send the object “calification”, then I want to validate all objects with BindingResult.hasErrors, is that possible?

    Sorry for my bad english, greetings from Mexico

Leave a Reply


8 − = six



Java Code Geeks and all content copyright © 2010-2015, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

Get ready to Rock!
To download the books, please verify your email address by following the instructions found on the email we just sent you.

THANK YOU!

Close