Consider the following mapping:
@RequestMapping(value = "/superDuperPage", method = RequestMethod.GET)
public String superDuperPage(@RequestParam(value = "someParameter", required = true) String parameter)
{
return "somePage";
}
I want to handle the missing parameter case by not adding in required = false
. By default, 400
error is returned, but I want to return, let's say, a different page. How can I achieve this?
An alternative
If you use the @ControllerAdvice on your class and if it extends the Spring base class ResponseEntityExceptionHandler. A pre-defined function has been created on the base class for this purpose. You have to override it in your handler.
This base class is very useful, especially if you want to process the validation errors that the framework creates.
You can do this with Spring 4.1 onwards and Java 8 by leveraging the Optional type. In your example that would mean your @RequestParam
String
will have now type ofOptional<String>
.Take a look at this article for an example showcasing this feature.
If a required
@RequestParam
is not present in the request, Spring will throw aMissingServletRequestParameterException
exception. You can define an@ExceptionHandler
in the same controller or in a@ControllerAdvice
to handle that exception:As the Spring documentation states: