Using JSR-303 with RESTful Web Services
The final topic we will discuss is the seamless support of Spring MVC with the JSR-303 Bean Validation
API. When using RESTful-WS, we can also apply the defined validation rule to the request arguments.
Let's revisit the Contact entity class and define a constraint on the firstName attribute. Listing 16-39
shows the code snippet of the revised getFirstName() method.
Listing 16-39. Revised getFirstName() Method of Contact Class
@NotNull
@Size(min=3, max=60)
@Column(name = "FIRST_NAME")
public String getFirstName() {
return firstName;
}
Then, in the ContactController class, in the create() method, add the @Valid annotation
(javax.validation.Valid) before the contact argument. Listing 16-40 shows the code snippet of the
revised create() method of the ContactController class.
Listing 16-40. Revised create() Method of ContactController Class
@RequestMapping(value="/", method=RequestMethod.POST)
@ResponseBody
public Contact create(@RequestBody @Valid Contact contact) {
logger.info("Creating contact: " + contact);
contactService.save(contact);
logger.info("Contact created successfully with info: " + contact);
return contact;
}
The differences from the previous version are in bold. The support of the @Valid annotation for the
argument was also introduced in Spring 3.1. With the annotation in place, Spring will perform JSR-303
validation to the Contact domain object after data binding, and exceptions will be thrown if violations
are found.
To see it in action, let's modified the insert operation of the RestfulClientSample class. Listing 16-41
shows the revised code snippet in the RestfulClientSample class for testing the insert operation.
Listing 16-41. Revised insert Operation of RestfulClientSample Class
// Testing create contact
System.out.println("Testing create contact :");
Contact contactNew = new Contact();
contactNew.setFirstName("JJ");
contactNew.setLastName("Gosling");
contactNew.setBirthDate(new DateTime());
contactNew = restTemplate.postForObject(
URL_CREATE_CONTACT, contactNew, Contact.class);
System.out.println("Contact created successfully: " + contactNew);
In Listing 16-41, the differences from the previous version are in bold. When setting the first name,
we intentionally set it to two characters only, which violates the rule (minimum three characters)
defined for the attribute.
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home