How does @RequestParam in Spring handle Guava's Optional?

后端 未结 3 1895
暗喜
暗喜 2021-02-05 02:36
@RequestMapping(value = \"/contact.html\", method = RequestMethod.POST)
public final ModelAndView contact(
        @RequestParam(value = \"name\", required = false) Opti         


        
3条回答
  •  梦谈多话
    2021-02-05 03:19

    The answer on you question will be optional parameter first is setting to null.

    In Spring HandlerMethodInvoker I found resolveRequestParam method

        Object paramValue = null;
        ...
        if (multipartRequest != null) {
        ...
        // Check if this is multipart request and set paramValue in this case.
        }
        // Otherwise
        if (paramValue == null) {
            String[] paramValues = webRequest.getParameterValues(paramName);
            if (paramValues != null) {
                paramValue = (paramValues.length == 1 ? paramValues[0] : paramValues);
            }
        }
        if (paramValue == null) {
           if (defaultValue != null) {
                paramValue = resolveDefaultValue(defaultValue);
            }
            else if (required) {
                raiseMissingParameterException(paramName, paramType);
            }
            ...
         }
         ...
    

    So first we check if it is a multipart request. Otherwise we get parameters values by parameter name from servlet request. Finally if parameter value null we check if parameter is required. If required we throw exception, otherwise return null.

提交回复
热议问题