Java Spring - how to handle missing required request parameters
If a required @RequestParam
is not present in the request, Spring will throw a MissingServletRequestParameterException
exception. You can define an @ExceptionHandler
in the same controller or in a @ControllerAdvice
to handle that exception:
@ExceptionHandler(MissingServletRequestParameterException.class)
public void handleMissingParams(MissingServletRequestParameterException ex) {
String name = ex.getParameterName();
System.out.println(name + " parameter is missing");
// Actual exception handling
}
I want to return let's say a different page. How to I achieve this?
As the Spring documentation states:
Much like standard controller methods annotated with a
@RequestMapping
annotation, the method arguments and return values of@ExceptionHandler
methods can be flexible. For example, theHttpServletRequest
can be accessed in Servlet environments and thePortletRequest
in Portlet environments. The return type can be aString
, which is interpreted as a view name, aModelAndView
object, aResponseEntity
, or you can also add the@ResponseBody
to have the method return value converted with message converters and written to the response stream.
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.
@Override
protected ResponseEntity<Object> handleMissingServletRequestParameter(MissingServletRequestParameterException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
String name = ex.getParameterName();
logger.error(name + " parameter is missing");
return super.handleMissingServletRequestParameter(ex, headers, status, request);
}
This base class is very useful, especially if you want to process the validation errors that the framework creates.