greengrassbluesky greengrassbluesky - 1 year ago 76
reST (reStructuredText) Question

Spring 3 - Annotation based Bean Validation

I am building a REST API. Its made up of a Resource ( @Controller ) which returns a response 204 even when one of the mandatory field is not present.

I am using Spring 3.1, validation-api (1.1.0.Final) & Hibernate-validator(4.3.0). Not sure if Hibernate-validator plays any role here.


I have a spring controller @Controller and a Bean with @Component

@Consumes(value = {MediaType.APPLICATION_JSON})
@Produces(value = {MediaType.APPLICATION_JSON})
@RequestMapping(method = RequestMethod.POST)
public Response addUserData(@Valid @RequestBody UserData userDataRequest) throws ResourceException {

My UserData bean has

public class UserData {

@NotNull(message = "user ID should not be null")
@Min(value = 1, message = "user ID should not be empty")
@Max(value = 20, message = "user ID should have length of more than 20")
@Pattern(regexp="[A-Z][a-z]+", message = "Only Alphanumeric characters allowed")
private String userId;


My validations are not getting executed. When I dont pass "userId", there is no error thrown. What am I missing here ?

Answer Source

I ultimately ended up using Jersey Bean Validation, instead of Spring. This is because rest of my code is using Jersey anyways. To make this work I just imported Jersey Bean Validation jar and added a small change to web.xml. Validations are now working.

Thank you @Manual Jordan. I will upvote your answer, since it gave me the right clues.

<!--  jersey beanValidation  -->
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download