Java Spring - 如何处理缺少的必需请求参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37746428/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 19:38:22  来源:igfitidea点击:

Java Spring - how to handle missing required request parameters

javaspringspring-mvc

提问by peech

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 notadding in required = false. By default, 400error is returned, but I want to return, let's say, a different page. How can I achieve this?

我想通过添加required = false. 默认情况下,400会返回错误,但我想返回一个不同的页面。我怎样才能做到这一点?

采纳答案by Ali Dehghani

If a required @RequestParamis not present in the request, Spring will throw a MissingServletRequestParameterExceptionexception. You can define an @ExceptionHandlerin the same controller or in a @ControllerAdviceto handle that exception:

如果@RequestParam请求中不存在required ,Spring 将抛出MissingServletRequestParameterException异常。您可以@ExceptionHandler在同一个控制器或 a 中定义一个@ControllerAdvice来处理该异常:

@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 documentationstates:

正如Spring 文档所述:

Much like standard controller methods annotated with a @RequestMappingannotation, the method arguments and return values of @ExceptionHandlermethods can be flexible. For example, the HttpServletRequestcan be accessed in Servlet environments and the PortletRequestin Portlet environments. The return type can be a String, which is interpreted as a view name, a ModelAndViewobject, a ResponseEntity, or you can also add the @ResponseBodyto have the method return value converted with message converters and written to the response stream.

就像用@RequestMapping注解注解的标准控制器方法一样,方法的参数和方法的返回值 @ExceptionHandler可以是灵活的。例如, HttpServletRequest可以在 Servlet 环境和 PortletRequestPortlet 环境中访问。返回类型可以是 a String,它被解释为视图名称ModelAndView对象、 a ResponseEntity,或者您也可以添加@ResponseBody以使方法返回值使用消息转换器转换并写入响应流。

回答by dimitrisli

You can do this with Spring 4.1onwards and Java 8by leveraging the Optionaltype. In your example that would mean your @RequestParamStringwill have now type of Optional<String>.

您可以通过利用Optional类型在Spring 4.1Java 8之后执行此操作。在您的示例中,这意味着您的@RequestParam现在将具有.StringOptional<String>

Take a look at this articlefor an example showcasing this feature.

请查看本文以获取展示此功能的示例。

回答by Eric Giguere

An alternative

替代

If you use the @ControllerAdviceon 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.

如果您在类上使用@ControllerAdvice并且它扩展了 Spring 基类ResponseEntityExceptionHandler。为此,在基类上创建了一个预定义的函数。您必须在处理程序中覆盖它。

    @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.

这个基类非常有用,特别是如果您想处理框架创建的验证错误。