concept @Valid in category java

appears as: @Valid
Portlets in Action

This is an excerpt from Manning's book Portlets in Action.

In Spring 3.0, you don’t need to programmatically validate your model attributes. Instead, you can use the @Valid annotation to validate the arguments of handler methods. The following listing shows the modified doSomething method, which makes use of the @Valid annotation.

Listing 8.20. The SomeController handler using the @Valid annotation

In listing 8.20, the @Valid annotation instructs Spring to validate the SomeObject model attribute. The validation and binding results are available to the doSomething method through the BindingResult object.

The validator set in listing 8.25 applies to all the model attributes of the portlet. The validation of a model attribute, which makes use of JSR 303 constraints, won’t happen unless the @Valid annotation is specified for the handler argument representing the model attribute. This next listing shows how AddBookController makes use of the @Valid annotation to validate the Book model attribute.

Listing 8.26. Using the @Valid annotation in the AddBookController

In listing 8.26, the @Valid annotation validates the Book model attribute when the AddBookController’s addBook handler method is invoked. The validation results are stored in the BindingResult object, like when you use the Spring Validation API. If you’re looking to programmatically validate your application objects using JSR 303, then you’ll have to deal directly with the JSR 303 API.

Listing 8.27 shows how AddBookController can be rewritten to programmatically perform validation. It’s important to note that when you’re using programmatic validation, you don’t need to configure the LocalValidatorFactoryBean for WebDataBinder (as was done in listing 8.25) or use the @Valid annotation in your handler method (as in listing 8.26). The LocalValidatorFactoryBean only needs to be defined in the web application context XML so that it’s available to the AddBookController handler.

sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage
test yourself with a liveTest