Spring Form Validation

This article covers the concepts of SimpleFormController, Spring Form Tags and Spring Validator.

First create a new Dynamic Web Project and configure it as Maven Project. For Reference, Click Here

Add the following dependencies in pom.xml

<properties>
    <spring.version>3.1.0.RELEASE</spring.version>
</properties>
 
<dependencies>
 
    <!-- Spring 3 dependencies -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${spring.version}</version>
    </dependency>
 
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>${spring.version}</version>
    </dependency>
 
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${spring.version}</version>
    </dependency>
 
</dependencies>

1. Controller

In order to handle spring forms, you need your controller to extend SimpleFormController. Following class shows you how to extend SimpleFormController

LoginController.java

package com.kruders.controller;
 
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
 
import com.kruders.domain.Login;
 
public class LoginController extends SimpleFormController{
    public LoginController(){
        setCommandClass(Login.class);
        setCommandName("loginForm");
    }
    @Override
    protected ModelAndView onSubmit(Object command) throws Exception {
        Login login = (Login) command;
        return new ModelAndView("loginSuccess","login",login);
    }
}

Extending SimpleFormController makes the controller to handle form requests. Here in LoginController contructor, controller will bind values to/from Spring’s form tags.

public LoginController(){
    setCommandClass(Login.class);  //Spring form values gets stored into Login object
    setCommandName("loginForm");    //if loginForm is submitted, Spring will forward request to this Controller
}

When loginForm is submitted, onsubmit() method will be executed to handle form’s request and return ModelAndView on success. All the forms field values will be submitted as Strings to the form controller.

2. Model

Following is the Login class.

package com.kruders.domain;
 
public class Login {
    String email;
    String password;
    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. Form Validation

To validate the form fields we have a seperate LoginValidator class that implements the Validator interface, override the validate() method perform all the validations.

Following in the LoginValidator class.

package com.kruders.validator;
 
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
 
import com.kruders.domain.Login;
 
public class LoginValidator implements Validator{
    @Override
    public boolean supports(Class<?> clazz) {
        return Login.class.isAssignableFrom(clazz);
    }
 
    @Override
    public void validate(Object target, Errors errors) {
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email", "email.required");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "password.required");
         
    }
}

4. Properties File

A properties file to store all the error messages. Here we have the error messages in a seperate properties file so we add the error code, you can even add the error messages directly.

messages.properties

email.required = User Name is required
password.required = Password is required

5. View

Following is the form login form that contains Spring’s Form Tags and display error message if any.

form:errors tag to display errors in jsp files.

loginForm.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login Page</title>
</head>
<body>
<form:form method="POST" commandName="loginForm">
    <table>
        <tr>
            <td>Email :</td>
            <td><form:input path="email" /></td>
            <td><form:errors path="email" cssClass="error" /></td>
        </tr>
        <tr>
            <td>Password :</td>
            <td><form:password path="password" /></td>
            <td><form:errors path="password" cssClass="error" /></td>
        </tr>
    </table>
    <tr>
            <td colspan="3"><input type="submit" value="Login"></td>
        </tr>
</form:form>
</body>
</html>

On successful submission of loginform, loginSuccess.jsp page will be displayed.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login Successful</title>
</head>
<body>
${login.email} successfully logged in<br/>
</body>
</html>

6. Spring Bean Configuration

We now declare the controller and validator for the loginform Spring Bean Configuration file.

<bean class="com.kruders.controller.LoginController">
    <property name="formView" value="loginForm" />
    <property name="successView" value="loginSuccess" />
  
    <!-- Map a validator -->
    <property name="validator">
        <bean class="com.kruders.validator.LoginValidator" />
    </property>
</bean>

Also add the properties file.

<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource" p:basename="messages" />

7. Run

Now when you run the project, following screen will be displayed as in Figure 8.1

Figure 8.1 Figure 8.1

Error messages will be shown if form is submitted with email and password fields empty as shown in Figure 8.2

Figure 8.2 Figure 8.2

On successful submission of form, following message is displayed as shown in Figure 8.3

Figure 8.3 Figure 8.3

The folder structure of the example is shown below in Figure 8.4

Figure 8.4 Figure 8.4

You can download the source code of this example here.

,

One Response to Spring Form Validation