Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
179 views
in Technique[技术] by (71.8m points)

java - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...