Java Spring - how to handle missing required reque

2020-05-19 07:31发布

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?

3条回答
女痞
2楼-- · 2020-05-19 08:22

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.

查看更多
We Are One
3楼-- · 2020-05-19 08:24

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 of Optional<String>.

Take a look at this article for an example showcasing this feature.

查看更多
霸刀☆藐视天下
4楼-- · 2020-05-19 08:30

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, the HttpServletRequest can be accessed in Servlet environments and the PortletRequest in Portlet environments. The return type can be a String, which is interpreted as a view name, a ModelAndView object, a ResponseEntity, or you can also add the @ResponseBody to have the method return value converted with message converters and written to the response stream.

查看更多
登录 后发表回答