Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Spring MVC : How to perform validation?

    • 0
    • 4
    • 2
    • 2
    • 0
    • 0
    • 0
    • 0
    • 531
    Comment on it

    Here I'm giving the example of validating form fields in a Spring Web MVC application using Bean Validation API. We'll develop a login form in Spring MVC in which we'll apply validation constraints on two fields email and password.

    We use the Bean Validation API to define validation constraints against properties of JavaBean objects. Here are the steps to define and use Bean Validation API:

    1. Bean Validation API and Hibernate Validator Implementation We declare validation constraints on object models via annotations by using Bean Validation API. For example:
    public class User {
                @NotNull
                @Email
                private String email;
    
                @NotNull
                @Size(min = 8, max = 16)
                private String password;
    
                // getters and setters
            }
         

    We will need the validation-api-1.1.0.Final.jar and hibernate-validator-5.0.1.Final.jar files to use the Bean Validation API in our application.

    Add the following dependencies to your pom.xml file:

    Bean Validation API 1.1:

    <dependency>
          <groupId>javax.validation</groupId>
          <artifactId>validation-api</artifactId>
          <version>1.1.0.Final</version>
    </dependency>
    

    Hibernate Validator 5.0.1.Final:

     <dependency>
          <groupId>org.hibernate</groupId>
          <artifactId>hibernate-validator</artifactId>
          <version>5.0.1.Final</version>
    </dependency>
    
    1. Write the below line into Springs application context XML file:
    <mvc:annotation-driven />
    

    By doing this Spring MVC container will detect and enable the validation support automatically.

    Now in the controller class, annotate the model object that is used as formbean by the @Valid annotation (javax.validation.Valid):

    @Controller
    public class LoginController {
    
        @RequestMapping(value = "/login", method = RequestMethod.POST)
        public String doLogin(@Valid User user, BindingResult result) {
            // write login logic here
        }
    }
    

    We can show validation error messages using the Springs form errors tag as follows:

    <form:errors path="email" />
    

    The error message can be specified in the validation annotation, for example:

    @NotEmpty(message = "Please enter your email addresss.")
    private String email;
    
    1. Define the model class

    User.java

    package com.evon;
    
    import javax.validation.constraints.Size;
    
    import org.hibernate.validator.constraints.Email;
    import org.hibernate.validator.constraints.NotEmpty;
    
    public class User {
    
        @NotEmpty(message = "Please enter your email addresss.")
        @Email
        private String email;
    
        @NotEmpty(message = "Please enter your password.")
        @Size(min = 8, max = 16, message = "Your password must between 8 and 16 characters")
        private 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;
        }
    }
    

    As we can see, the validation constraint annotations used here are: @NotEmpty, @Email and @Size.

    1. Define the JSP file

    login.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <%@ 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>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Login</title>
    <style>
        .error {
            color: red; font-weight: bold;
        }
    </style>
    </head>
    <body>
        <div align="center">
            <h2>Spring MVC Validation Demo - Login Form</h2>
            <table border="0" width="90%">
            <form:form action="login" commandName="userForm">
                    <tr>
                        <td align="left" width="20%">Email: </td>
                        <td align="left" width="40%"><form:input path="email" size="30"/></td>
                        <td align="left"><form:errors path="email" cssClass="error"/></td>
                    </tr>
                    <tr>
                        <td>Password: </td>
                        <td><form:password path="password" size="30"/></td>
                        <td><form:errors path="password" cssClass="error"/></td>
                    </tr>
                    <tr>
                        <td></td>
                        <td align="center"><input type="submit" value="Login"/></td>
                        <td></td>
                    </tr>
            </form:form>
            </table>
        </div>
    </body>
    </html>
    
    1. Define the Controller class

    LoginController.java

    package com.java;
    
    import java.util.Map;
    
    import javax.validation.Valid;
    
    import org.springframework.stereotype.Controller;
    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;
    
    
    @Controller
    public class LoginController {
        @RequestMapping(value = "/login", method = RequestMethod.GET)
        public String viewLogin(Map<String, Object> model) {
            User user = new User();
            model.put("userForm", user);
            return "login";
        }
    
        @RequestMapping(value = "/login", method = RequestMethod.POST)
        public String doLogin(@Valid @ModelAttribute("userForm") User userForm,
                BindingResult result, Map<String, Object> model) {
    
            if (result.hasErrors()) {
                return "login";
            }
    
            return "success";
        }
    }
    
    1. Define the login success Page

    success.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!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=UTF-8">
    <title>Welcome</title>
    </head>
    <body>
        <div>
            <h2>Welcome ${userForm.email}! You have logged in successfully.</h2>
        </div>
    </body>
    </html>
    
    1. Now define the applicationContext.xml as below:
    <?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-3.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd   
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    
        <mvc:annotation-driven />
        <context:component-scan base-package="com.evon" />
    
        <bean id="viewResolver"
            class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/WEB-INF/views/" />
            <property name="suffix" value=".jsp" />
        </bean>
    
    
        <bean id="messageSource"
            class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
    
            <property name="basename" value="/WEB-INF/messages" />
    
        </bean>
    </beans>  
    
    1. 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"
            id="WebApp_ID" version="3.0">
        <display-name>SpringValidation</display-name>
    
        <servlet>
            <servlet-name>dispatcherServlet</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>/WEB-INF/spring-mvc.xml</param-value>
            </init-param>
            <load-on-startup>1</load-on-startup>
        </servlet>
    
        <servlet-mapping>
            <servlet-name>dispatcherServlet</servlet-name>
            <url-pattern>/</url-pattern>
        </servlet-mapping>
    </web-app>
    
    1. The required JAR files under the WEB-INF\lib directory are:
    classmate-0.5.4.jar
    commons-logging-1.1.1.jar
    hibernate-validator-5.0.1.Final.jar
    jboss-logging-3.1.0.GA.jar
    spring-beans-3.2.4.RELEASE.jar
    spring-context-3.2.4.RELEASE.jar
    spring-core-3.2.4.RELEASE.jar
    spring-expression-3.2.4.RELEASE.jar
    spring-web-3.2.4.RELEASE.jar
    spring-webmvc-3.2.4.RELEASE.jar
    validation-api-1.1.0.Final.jar
    

    Note that the Hibernate Validator JAR file depends on Classmate and JBoss logging JAR files.

    1. Type the following URL into your browsers address bar:
    http://localhost:8080/SpringValidation/login
    

    You'll get the login form, if you provide a valid email and valid password (between 8 and 16 characters) you will get login success page otherwise you will get errors.

    Hope this will help :)

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: