java Spring MVC 如何转换 @RequestParam 值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29804388/
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-11-02 15:58:24  来源:igfitidea点击:

How does Spring MVC convert @RequestParam values?

javaspringspring-mvcannotations

提问by WannabeCoder

I'm new to the Spring Framework, and as a symptom, I want to keep my adoption of its Web MVC portions as simple as possible, so I'm using the annotation functions to work with Spring. In the past, I've used:
int value = Integer.valueOf(request.getParameter("numberValue"))
to pull values from parameters - explicitly converting the String returned by getParameter().
Helpfully, I've noticed that when I use Spring's terminology:
@RequestParameter("numberValue") int numVal
the conversion is handled automatically. This is nice, but a "black box" to me. I tried looking at questions on here or in the Spring documentation, but all that information deals with custom conversions (like Converter) for objects or formatting issues. All I want to know is how Spring handles primitive type conversions for @RequestParamby default.

我是 Spring 框架的新手,作为一个症状,我希望尽可能简单地采用其 Web MVC 部分,因此我使用注释函数来处理 Spring。过去,我使用过:
int value = Integer.valueOf(request.getParameter("numberValue"))
从参数中提取值 - 显式转换getParameter().
有用的是,我注意到当我使用 Spring 的术语时:
@RequestParameter("numberValue") int numVal
转换是自动处理的。这很好,但对我来说是一个“黑匣子”。我尝试查看此处或 Spring 文档中的问题,但所有这些信息都涉及对象或格式问题的自定义转换(如 Converter)。我只想知道 Spring@RequestParam默认如何处理原始类型转换。

回答by Dev

I've noticed that when I use Spring's terminology: @RequestParameter("numberValue") int numVal the conversion is handled automatically.

我注意到当我使用 Spring 的术语时:@RequestParameter("numberValue") int numVal 转换是自动处理的。

Here you are looking for Type Conversion

在这里你正在寻找类型转换

As per spring documentation given on this link

根据此链接上给出的 spring 文档

String-based values extracted from the request including request parameters, path variables, request headers, and cookie values may need to be converted to the target type of the method parameter or field (e.g., binding a request parameter to a field in an @ModelAttribute parameter) they're bound to. If the target type is not String, Spring automatically converts to the appropriate type. All simple types such as int, long, Date, etc. are supported.

从请求中提取的基于字符串的值,包括请求参数、路径变量、请求头和 cookie 值,可能需要转换为方法参数或字段的目标类型(例如,将请求参数绑定到@ModelAttribute 中的字段)参数)他们绑定到。如果目标类型不是 String,Spring 会自动转换为合适的类型。支持所有简单类型,例如 int、long、Date 等。