Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validation in Spring MVC

how to get the request object in the validator class, as i need to validate the contents ie the parameters present in the request object.

like image 639
Darshan.R Avatar asked Apr 07 '11 06:04

Darshan.R


People also ask

What is validation Spring MVC?

The Spring MVC Validation is used to restrict the input provided by the user. To validate the user's input, the Spring 4 or higher version supports and use Bean Validation API. It can validate both server-side as well as client-side applications.

What is Validator in Spring?

Spring features a Validator interface that you can use to validate objects. The Validator interface works using an Errors object so that while validating, validators can report validation failures to the Errors object.

What is custom validation in Spring?

It is necessary to validate user input in any web application to ensure the processing of valid data. The Spring MVC framework supports the use of validation API. The validation API puts constraints on the user input using annotations and can validate both client-side and server-side.

What is Bean Validation in Spring?

Data validation is a basic requirement for any application. This is more significant for web applications that accept data as input. Bean Validation or commonly known as JSR-380 is a Java standard that is used to perform validation in Java applications. To perform validation, data Items are applied constraints.


1 Answers

You have two choices:

  • JSR 303 (Bean Validation) Validators
  • Spring Validators

For JSR 303 you need Spring 3.0 and must annotate your Model class with JSR 303 Annotations, and write an @Valid in front of you parameter in the Web Controller Handler Method. (like Willie Wheeler show in his answer). Additionaly you must enable this functionality in the configuration:

<!-- JSR-303 support will be detected on classpath and enabled automatically -->
<mvc:annotation-driven/>

For Spring Validators, you need to write your Validator (see Jigar Joshi's answer) that implements the org.springframework.validation.Validator Interface. The you must register your Validator in the Controller. In Spring 3.0 you can do this in a @InitBinder annotated Method, by using WebDataBinder.setValidator (setValidator it is a method of the super class DataBinder)

Example (from the spring docu)
@Controller
public class MyController {

    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        binder.setValidator(new FooValidator());
    }

    @RequestMapping("/foo", method=RequestMethod.POST)
    public void processFoo(@Valid Foo foo) { ... }
}

For more details, have a look at the Spring reference, Chapter 5.7.4 Spring MVC 3 Validation.

BTW: in Spring 2 there was someting like a setValidator property in the SimpleFormController.

like image 193
Ralph Avatar answered Oct 31 '22 19:10

Ralph