我有一个带有 get 方法的 Controller ,该方法接收 3 个参数作为 java.lang.Integer
@GetMapping(path = Constantes.CONSULTAR_NODO_SUCESOR)
public ConsultarNodoSucesorResponse consultarNodoSucesor(@RequestHeader HttpHeaders headerRequest,
@RequestParam(required = false) Integer idArbol,
@RequestParam(required = false) Integer nivelFormulario,
@RequestParam(required = false) Integer idSucesor,
@RequestParam(required = false) String rutaRelacion,
@RequestParam(required = false) String tipoRelacion,
HttpServletResponse headerResponse) {
ConsultarNodoSucesorRequest request = new ConsultarNodoSucesorRequest(idArbol, nivelFormulario, idSucesor,
rutaRelacion, tipoRelacion);
return service.consultarNodoSucesor(headerRequest, request, headerResponse);
}
当服务器因错误请求而返回代码 400 时,完整错误如下
Failed to convert value of type 'java.lang.String' to required type 'java.lang.Integer'; nested exception is java.lang.NumberFormatException: For input string: \"4111111111\
我在参数 idArbol
中发送值 4111111111,但它不起作用,另一方面,当我发送相同的参数值(如 1044444444)时,它工作正常。
为什么会出现这样的情况呢? 整数的最大值是多少
最佳答案
与值 1044444444
不同,值 4111111111
对于 int
(因此是 Integer
)数据来说太大类型,因此被理解为String
。该值超出了整数允许的范围。
int: By default, the int data type is a 32-bit signed two's complement integer, which has a minimum value of -231 and a maximum value of 231-1.
你可能想知道为什么 Spring 会有这样的行为。这是Type Conversion Spring的几个注解的特点,其中String
是默认值:
Some annotated controller method arguments that represent String-based request input (such as
@RequestParam
,@RequestHeader
,@PathVariable
,@MatrixVariable
, and@CookieValue
) can require type conversion if the argument is declared as something other than String.For such cases, type conversion is automatically applied based on the configured converters. By default, simple types (
int
,long
,Date
, and others) are supported. You can customize type conversion through aWebDataBinder
(seeDataBinder
) or by registering Formatters with theFormattingConversionServic
e. See Spring Field Formatting.
关于java - ResourceController 上的 NumberFormatException 无法从字符串转换为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59760132/