Loading...

Spring MVC Custom Validator Example in java

View: 555    Dowload: 0   Comment: 0   Post by: hanhga   Category: Javascript   Fields: Other

In spring mvc form submit tutorial, we learned about displaying displaying a form and submitting form data, including validating inputs using BindingResult.rejectValue(). In this example, we will learn to build a more robust validator for EmployeeVO model object. This validator is custom implementation of Validatorinterface. In this example, I am modifying the code used for form submit example we built in last tutorial.

Custom Validator Implementation

Spring MVC supports validation by means of a validator object that implements the Validator interface. You can write the following validator to check if the required form fields are filled.

package com.howtodoinjava.demo.validator;
 
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
 
import com.howtodoinjava.demo.model.EmployeeVO;
 
@Component
public class EmployeeValidator implements Validator 
{
 
    public boolean supports(Class clazz) {
        return EmployeeVO.class.isAssignableFrom(clazz);
    }
 
    public void validate(Object target, Errors errors) 
    {
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName", "error.firstName", "First name is required.");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lastName", "error.lastName", "Last name is required.");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email", "error.email", "Email is required.");
    }

}

In this validator, you use utility methods such as rejectIfEmptyOrWhitespace() and rejectIfEmpty() in theValidationUtils class to validate the required form fields. If any of these form fields is empty, these methods will create a field error and bind it to the field. The second argument of these methods is the property name, while the third and fourth are the error code and default error message.

Many times validation errors are not specific to fields. For example end date should be greater than start date. In this case, you can use the reject() method to create an object error to be bound to the EmployeeVO object, not to a field.

e.g. errors.reject(“invalid.dateDiff”, “End date should be greater than start date.”);

To activate this custom validator as a spring managed bean, you need to do one of following things:

1) Add @Component annotation to EmployeeValidator class and activate annotation scanning on the package containing such declarations.

<context:component-scan base-package="com.howtodoinjava.demo" />

2) Alternatively, you can register the validator class bean directly in context file.

<bean id="employeeValidator" class="com.howtodoinjava.demo.validator.EmployeeValidator" />

Controller Changes

To apply this validator, you need to perform the following modification to your controller.

1) Include validator reference to controller class and mark it autowired to ensure it’s available when needed

@Autowired
EmployeeValidator validator;

2) Next change is in controller’s post method which is called when user submit the form.

@RequestMapping(method = RequestMethod.POST)
public String submitForm(@ModelAttribute("employee") EmployeeVO employeeVO,
                        BindingResult result, SessionStatus status) 
{
     
    //Validation code
    validator.validate(employeeVO, result);
     
    //Check validation errors
    if (result.hasErrors()) {
        return "addEmployee";
    }
     
    //Store the employee information in database
    //manager.createNewRecord(employeeVO);
     
    //Mark Session Complete
    status.setComplete();
    return "redirect:addNew/success";
}

Once the validate method returns, the result parameter i.e. BindingResult contains the results for the validation process. You can check if there was any error in input using result.hasErrors() method call. If any error is detected you can again render the form view to let user correct it’s input.

If there is no error found then result.hasErrors() will return false, then you can simply process the input and redirect the user to next view.

Complete sourcecode foe controller used in this example is below:

package com.howtodoinjava.demo.controller;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
 
import com.howtodoinjava.demo.model.EmployeeVO;
import com.howtodoinjava.demo.service.EmployeeManager;
import com.howtodoinjava.demo.validator.EmployeeValidator;
 
@Controller
@RequestMapping("/employee-module/addNew")
@SessionAttributes("employee")
public class EmployeeController 
{
    @Autowired
    EmployeeManager manager;
     
    @Autowired
    EmployeeValidator validator;
     
    @RequestMapping(method = RequestMethod.GET)
    public String setupForm(Model model) 
    {
         EmployeeVO employeeVO = new EmployeeVO();
         model.addAttribute("employee", employeeVO);
         return "addEmployee";
    }
     
    @RequestMapping(method = RequestMethod.POST)
    public String submitForm(@ModelAttribute("employee") EmployeeVO employeeVO,
                            BindingResult result, SessionStatus status) 
    {
         
        validator.validate(employeeVO, result);
         
        if (result.hasErrors()) {
            return "addEmployee";
        }
        //Store the employee information in database
        //manager.createNewRecord(employeeVO);
         
        //Mark Session Complete
        status.setComplete();
        return "redirect:addNew/success";
    }
     
    @RequestMapping(value = "/success", method = RequestMethod.GET)
    public String success(Model model) 
    {
         return "addSuccess";
    }
}

Drop me you questions into comments section.

Spring MVC Custom Validator Example in java

In spring mvc form submit tutorial, we learned about displaying displaying a form and submitting form data, including validating inputs using BindingResult.rejectValue()

Posted on 02-08-2016 

Comment:

To comment you must be logged in members.

Files with category

  • Mini Youtube Using ReactJS

    Mini Youtube Using ReactJS

    View: 237    Download: 3   Comment: 0

    Category: Javascript     Fields: none

    This is one the best starter for ReactJS. MiniYoutube as the name suggests is a youtube like website developed using reactJS and youtube API. This project actually let's you search , play and list youtube videos. Do check it out and start learning...

  • AngularJS and REST API

    AngularJS and REST API

    View: 369    Download: 0   Comment: 0

    Category: Javascript     Fields: Other

    This is a tutorial for those interested in a quick introduction to AngularJS and REST API. We will build the familiar Periodic Table of the Elements found in every chemistry textbook, and allow the user to select a Chemical Element by clicking on...

  • Collective Intelligence, Recommending Items Based on Similar Users' Taste

    Collective Intelligence, Recommending Items Based on Similar Users' Taste

    View: 301    Download: 0   Comment: 0

    Category: Javascript     Fields: Other

    Using Collaborative Filtering to find people who share tastes, and for making automatic recommendations based on things that other people like.

  • Think Like a Bird for Better Parallel Programming

    Think Like a Bird for Better Parallel Programming

    View: 278    Download: 0   Comment: 0

    Category: Javascript     Fields: Other

    Coding an application to run in parallel is hard, right? I mean, it must be hard or we’d see parallel programs everywhere. All we'd see are slick parallel apps that use every available core effortlessly. Instead multi-threaded apps are the exception...

  • Getting Started with the Bing Search APIs

    Getting Started with the Bing Search APIs

    View: 302    Download: 0   Comment: 0

    Category: Javascript     Fields: Other

    Bing Search API is a set of REST interfaces that find web pages, news, images, videos, entities, related searches, spelling corrections, and more in response to queries from any programming language that can generate a web request. Applications that...

  • Brief Introduction of SocketPro High Performance and Scalable Persistent Message Queue

    Brief Introduction of SocketPro High Performance and Scalable Persistent Message Queue

    View: 676    Download: 0   Comment: 0

    Category: Javascript     Fields: Other

    Continuous in-line request/result batching, real-time stream sending/processing, asynchronous data transferring and parallel computation for best performance and scalability

  • Iteration Over Java Collections with High Performance

    Iteration Over Java Collections with High Performance

    View: 279    Download: 0   Comment: 0

    Category: Javascript     Fields: Other

    Java developers usually deal with Collections such as ArrayList, HashSet, Java 8 come with lambda and streaming API helps us to easily work with Collections. In most cases, we work with few thousands of items and performance isn't a concern. But in...

  • SR2JLIB - A Symbolic Regression Library for Java

    SR2JLIB - A Symbolic Regression Library for Java

    View: 282    Download: 0   Comment: 0

    Category: Javascript     Fields: Other

    Grammar-Guided Genetic Programming library featuring: multi-threading, just-in-time compilation of individuals, dynamic class loading, and JNI interfacing with C/C++ code

 
File suggestion for you
Loading...
File top downloads
Loading...
Loading...
Codetitle - library source code to share, download the file to the community
Copyright © 2018. All rights reserved. codetitle Develope by Vinagon .Ltd