Search code examples
javaspringspring-mvcspring-annotations

How to validate request parameters in Spring?


Here s my CODE to start with:

PersonController.java

@RequestMapping(value = "/person", method = RequestMethod.POST)
    public ResponseEntity<?> addPerson(@Valid Person p, HttpServletResponse response) {
        ...
    }

Person.java

public class Person {    

    @NotNull
    String name;    

    @NotNull
    int age;    

    String gender;
}

The requirement is: When a POST request is made to /person, I want an exception to be thrown if the user did not specify a key for the string Name in the BODY of the request. The annotation @NotNull does not do this.

Is there another annotation that I can use in Person.java to achieve this? If not, is there some validation I could do in the addPerson method to ensure that an exception is thrown if one of the mandatory parameters are not there?


Solution

  • Actually the @NotNull annotation does exactly what you want but unfortunately it can't do it on int type since it can't be null. In order for it to work you need to change the age to Integer and then after the spring does the binding of values if both parameters are passed and they have values the validation will pass. Otherwise if they are passed with empty value or not passed at all the value will be null and the validation will fail. Just make sure that you don't have some constructor for Person that initializes the attributes to some values.

    If you don't want to change it and use an int you can add HttpServletRequest request to the method arguments and check if there is a parameter age present with:

    request.getParameter('age');
    

    If it is null then no parameter was passed at all.

    Hint: It may be that you are missing some configuration and the annotation are not processed at all, something like <mvc:annotation-driven/> or @EnableWebMvc or maybe you are missing an actual validator implementation like Hibernate Validator. It is hard to tell without a sample of your configuration.