Validators in Spring MVC by R4R Team

Validators in Spring MVC:-

A Spring validator is an optional class that can be invoked for validating form data for a given command (form) controller.This validator class is a concrete class that implements the org.springframework.validation.Validator interface. One of the two methods required by this interface is the validate method, which is passed a command object, as mentioned previously, and an Errors object, which can be used to return errors. I will demonstrate an example of a Validator class later in this chapter.Another notable validation class is org.springframework.validation.ValidationUtils, which provides convenient methods for rejecting empty fields.

We use @Min, @Max, @NotNull etc annotations for server side validations in spring MVC.Thses annotations should be place in Model Class.

For example:-
I have an class Person with properties Name,Gender,Email. If I put @NotNull annotation on email property then it will get apply globaly, if my requirment get changed like if in my system there are two persons Student and Teacher and for Teacher registration email is optional but for Student its not null then how can i achive this.
 

1 Person.java

class Person {

@NotNull(groups = StudentChecks.class)

@Email

private email;

// other members with getters/setters

public interface StudentChecks {

}}

2 StudentController.java

@Controller

public class StudentController {

@RequestMapping(value = "/students", method = RequestMethod.POST)

public String createStudent(@Validated({Person.StudentChecks.class}) Person student, BindingResult result) {

// your code

}}

Leave a Comment:
Search
Categories
R4R Team
R4Rin Top Tutorials are Core Java,Hibernate ,Spring,Sturts.The content on R4R.in website is done by expert team not only with the help of books but along with the strong professional knowledge in all context like coding,designing, marketing,etc!