Spring MVC 如何转换 @RequestParam 值? [英] How does Spring MVC convert @RequestParam values?

查看:37
本文介绍了Spring MVC 如何转换 @RequestParam 值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 @RequestParam by default.

推荐答案

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

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

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

Here you are looking for Type Conversion

根据此 链接

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

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.

这篇关于Spring MVC 如何转换 @RequestParam 值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆