Spring MVC Validations Tutorial


Hi friends,Today I am going to tell you about spring validations . Validations are important part of any application  are applied on the input given by user.In Spring there are some predefined validations which we can use in our application.

Let us first execute the project step by step and at last I ll explain you the steps in detail. In same manner as I show you in Spring MVC Hello World Tutorial , we ll create a new Dynamic Project . I f you haven't read about Spring Basics like Spring Flow and Basic Hello World Program the I  ll advise you to first go through them . Now let us learn validations step by step .


What you ll require :

1.validation-api-1.0.0.[JSR-303]

2.hibernate-validator-4.2.0.Final


  • Spring annotation validations are also known as JSR-303 validations
  • We need to import javax.validation.constraints.* and org.hibernate.validator.constraints.*



Step 1: As we have some bean class as:

import org.hibernate.validator.constraints.NotEmpty;
import javax.validation.constraints.Size;
public class JavaInHouseBean{

    @NotEmpty
    private String user;

    @NotEmpty(message = "Password should not be blank.")
    @Size(min = 5, max = 8, message = "Password length should be between 5 to 8 Characters.")
    private String password;

    // Setters and Getters...
}



Step 2: Controller class :

@Controller
public class JavaInHouseController {  

        @RequestMapping("/login")
        public String loginCheck(@Valid JavaInHouseBean bean, BindingResult result, ModelMap model) {

            if (result.hasErrors()) {
                return "loginPage";
            } else {
                model.addAttribute("loginobj", bean);
                return "success";
            }
        }            
}

Step 3:  In spring configuration file means file which is *-spring.xml you need to add

<mvc:annotation-driven />  so that JSR-303 annotations ll be activated.

after line <context:component-scan base-package="javainhouse" />


Now your validations should work perfectly and error message should be shown on view.

Explanation : In JavaInHouseController.java , I have written @Valid JavaInHouseBean bean right, means once the flow came to this line and as we are using @Valid annotation, flow will redirect to JavaInHouseBean and annotation validations will be executed. If  get any errors all those errors will be added to the BindingResult object automatically.  We can consider this BindingResult object as response in java servlets.

If you are facing any errors or any suggestions please comment below :)



Post a Comment