1

I am working on a Spring REST application.
This application has only REST controllers, no view part.

I want to know how can I validate a @RequestParam

For example

@RequestMapping(value = "", params = "from", method = RequestMethod.GET)
    public List<MealReadingDTO> getAllMealReadingsAfter(@RequestParam(name = "from", required = true) Date fromDate) {
......
......
}

In the above example, my goal is to validate the Date. Suppose someone pass an invalid value, then I should be able to handle that situation.
Now it is giving and exception with 500 status.

PS
My question is not just about Date validation.
Suppose, there is a boolean parameter and someone passes tru instead of true by mistake, I should be able to handle this situation as well.

Thanks in advance :)

2
  • looks like you need to implement a custom validation Commented Jul 8, 2016 at 9:50
  • @MarcoAcierno how can I do that, can you provide me a link or something. Thanks :) Commented Jul 8, 2016 at 9:54

1 Answer 1

3

Spring will fail with an 500 status code, because it cannot parse the value.

The stages of request handling are:

  1. receive request
  2. identify endpoint
  3. parse request params / body values and bind them to the detected objects
  4. validate values if @Validated is used
  5. enter method call with proper parameters

In your case the flow fails at the parse (3) phase.

Most probably you receive a BindException. You may handle these cases by providing an exception handler for your controller.

@ControllerAdvice
public class ControllerExceptionHandler {
     @ExceptionHandler(BindException.class)
     @ResponseStatus(HttpStatus.BAD_REQUEST)
     @ResponseBody
     public YourErrorObject handleBindException(BindException e) {
         // the details which field binding went wrong are in the 
         // exception object. 
         return yourCustomErrorData;
     }
}

Otherwise when parsing is not functioning as expected (especially a hussle with Dates), you may want to add your custom mappers / serializers.

Most probably you have to configure Jackson, as that package is responsible for serializing / deserializing values.

Sign up to request clarification or add additional context in comments.

1 Comment

Let me try this one, Thanks :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.