当前位置:网站首页>Code skills - Controller Parameter annotation @requestparam
Code skills - Controller Parameter annotation @requestparam
2022-07-02 06:24:00 【Qihai Jianren】
This article introduces Controller Parameter annotation @RequestParam How to use , Precautions for use , As well as HttpServletRequest#getParameter Differences in methods ;
1. annotation @RequestParam The role of
(1) yes SpringMVC Receive comments for common parameters in , Notes are typed in Controller On the method parameters ;
(2) Can be URL Request parameter mapping is bound to Controller On the method parameters , Convenient for business receiving and processing HTTP Request parameters ;
(3) Through the attributes of annotations , It can be done to Controller Parameters do some simple " Verification is required " and " The default value fills in ";
2. annotation @RequestParam Parameter description
Reference resources :org.springframework.web.bind.annotation.RequestParam
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RequestParam {
/**
* Alias for {@link #name}.
*/
@AliasFor("name")
String value() default "";
/**
* The name of the request parameter to bind to.
* @since 4.2
*/
@AliasFor("value")
String name() default "";
/**
* Whether the parameter is required.
* <p>Defaults to {@code true}, leading to an exception being thrown
* if the parameter is missing in the request. Switch this to
* {@code false} if you prefer a {@code null} value if the parameter is
* not present in the request.
* <p>Alternatively, provide a {@link #defaultValue}, which implicitly
* sets this flag to {@code false}.
*/
boolean required() default true;
/**
* The default value to use as a fallback when the request parameter is
* not provided or has an empty value.
* <p>Supplying a default value implicitly sets {@link #required} to
* {@code false}.
*/
String defaultValue() default ValueConstants.DEFAULT_NONE;
}
explain :
- value:name Alias for property , The same effect ;
- name:URL Parameter name in , Map to the parameter corresponding to the current annotation ; If the property is not set , The method parameter name matches the interface parameter name ;
- required: The default value is "true", Indicates that the request path must contain the parameter , If not, it will be reported 404 Error code ;
- defaultValue:String type , Default parameter value , If the value is set , attribute required=true Will fail , Automatically for false; If the parameter is not passed , Just use the default values ; The default value can also be SpEL expression ;
3. Examples of use
(1)name attribute
@RequestMapping(value = "/testParams", method = RequestMethod.POST)
public BaseResponse<String> testParams(HttpServletRequest request, @RequestParam(name = "pkgName") String packageName) {
log.warn("[request.getParameterMap={} request.getParameter(\"packageName\")={} packageName={}]",
JSON.toJSONString(request.getParameterMap()),
request.getParameter("packageName"),
packageName);
return BaseResponse.success("ok");
}
Console output :
[request.getParameterMap={"pkgName":["com.ee.test.aaa"]} request.getParameter("pkgName")=com.ee.test.aaa packageName=com.ee.test.aaa]
URL The parameter name in is "pkgName", Through annotation name attribute ,Controller Method parameters use "packageName" To receive parameters ;
(2)required attribute
Default require=true, If this parameter is not passed, an error will be reported ;
Console MissingServletRequestParameterException abnormal :
org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'pkgName' is not present
require=false, You don't need to pass this parameter ;
@RequestMapping(value = "/testParams", method = RequestMethod.POST)
public BaseResponse<String> testParams(HttpServletRequest request, @RequestParam(name = "pkgName", required = false) String packageName) {
log.warn("[request.getParameterMap={} request.getParameter(\"pkgName\")={} packageName={}]",
JSON.toJSONString(request.getParameterMap()),
request.getParameter("pkgName"),
packageName);
return BaseResponse.success("ok");
}
(3)defaultValue attribute
If the value is set , attribute required=true Will fail ,URL When this parameter is not transmitted , Default values will be used ;
@RequestMapping(value = "/testParams", method = RequestMethod.POST)
public BaseResponse<String> testParams(HttpServletRequest request,
@RequestParam(name = "pkgName", defaultValue = "defaultPkgName") String packageName) {
log.warn("[request.getParameterMap={} request.getParameter(\"pkgName\")={} packageName={}]",
JSON.toJSONString(request.getParameterMap()),
request.getParameter("pkgName"),
packageName);
return BaseResponse.success("ok");
}
Console output :
[request.getParameterMap={} request.getParameter("pkgName")=null packageName=defaultPkgName]
Type conversion , here defaultValue by String type , Parameter type is Integer, take defaultValue Set up 100, You can see that simple types can be converted automatically :
@RequestMapping(value = "/testParams1", method = RequestMethod.POST)
public BaseResponse<String> testParams1(HttpServletRequest request,
@RequestParam(name = "appId", defaultValue = "100") Integer id) {
log.warn("[request.getParameterMap={} request.getParameter(\"appId\")={} id={}]",
JSON.toJSONString(request.getParameterMap()),
request.getParameter("appId"),
id);
return BaseResponse.success("ok");
}
[request.getParameterMap={} request.getParameter("appId")=null id=100]
If Controller Parameter type is Integer The default value is not the string corresponding to the numeric type , An error will be reported when requesting. The method parameter is wrong :
@RequestMapping(value = "/testParams2", method = RequestMethod.POST)
public BaseResponse<String> testParams2(HttpServletRequest request,
@RequestParam(name = "appId", defaultValue = "defaultAppId") Integer id) {
log.warn("[request.getParameterMap={} request.getParameter(\"appId\")={} id={}]",
JSON.toJSONString(request.getParameterMap()),
request.getParameter("appId"),
id);
return BaseResponse.success("ok");
}
MethodArgumentTypeMismatchException, bad param type: bad params type: id required type java.lang.Integer
4. You can also not use @RequestParam annotation —— The difference between adding and not adding notes
Don't use @RequestParam annotation ,URL Parameters can still be received ;
// Receive parameters without comments
@RequestMapping("/test1")
public String test1(int userId) {
return "list";
}
// Annotate the receiving parameters
@RequestMapping("/test2")
public String test2(@RequestParam int userId) {
return "list";
}
Manifested as :
(1) No addition @RequestParam when , The requested parameter name needs and Controller The method parameter names of must be consistent to take effect ; Use @RequestParam when , Can pass @RequestParam(“userId”) perhaps @RequestParam(value = “userId”) Specify the passed in parameter name ;
(2) No addition @RequestParam when , Parameters are not required , Add @RequestParam Without specifying annotation attributes require=false when , Parameters are required ; And through @RequestParam(defaultValue = “0”) Specify parameter defaults ;
5. annotation @RequestParam And HttpServletRequest#getParameter Differences in methods
request.getParameter("name") and @RequestParam String name The way of obtaining is different , The comparison is as follows :
HttpServletRequest#getParameter
(1) request.getParameter(String name): obtain name Corresponding value, If there are more than one , Return to the first ;
(2) request.getParameterNames(): obtain request All in name, return Enumeration type ;
(3) request.getParameterValues(String name): obtain name All corresponding value;
In fact, these three methods are from a global variable Map<String, String[]> The value obtained in , thus it can be seen :key yes String type , That is to say name, and value yes String An array type , You can provide multiple identical key,value Value to request , Here is an example ;
The request parameter has the same parameter name , Pass in two different values :
Console results :
[request.getParameterMap={"pkgName":["AAA","BBB"]} request.getParameter("pkgName")=AAA packageName=AAA,BBB]
so :
- Map Are all parameters K/V,V Is an array type , When the same parameter passes multiple values , Add array ;
- request.getParameter Will take the first value in the array , Here is the AAA;
- Controller Method parameter packageName What you receive is the result of splicing multiple values in the array , Here is the =AAA,BBB;
From the above results , At least you know ,@RequestParam And request.getParameter The logic is different , Let's have a look :
The answer is found , Complete the string splicing here ;
From the source ,@RequestParam And request.getParameter The logic is different , What's actually called is getParameterValues Method , This method returns String Array , And the source code made a judgment , The array is not null Under the circumstances , If the array length is 1 Returns the first element , If not ( Greater than 1) Returns the current array , And pass Spring Bag StringUtils Convert an array to a string , Put together a comma ;
Conclusion :request.getParameter and @RequestParam It's essentially different , So I'm not sure if there are more value Under the circumstances ,@RequestParam It can't replace request.getParameter To use the !
Use of norms @RequestParam The way of writing should be @RequestParam String[] packageNames, as follows :
and request.getParameter The acquisition is really the first value, Maybe we seldom encounter many of the same in the process of R & D key Submit the request , But this situation is real , If you don't know this code , Or the @RequestParam Use as the first parameter , Sooner or later something will go wrong !
Reference resources :
@RequestParam Detailed explanation
request.getParameter() and @RequestParam The difference between
边栏推荐
- Is there a really free applet?
- Top 10 classic MySQL errors
- New version of dedecms collection and release plug-in tutorial tool
- Zhuanzhuanben - LAN construction - Notes
- Arduino Wire 库使用
- 最新CUDA环境配置(Win10 + CUDA 11.6 + VS2019)
- Codeforces Round #797 (Div. 3) A—E
- LeetCode 78. subset
- BGP中的状态机
- Google play academy team PK competition, official start!
猜你喜欢
Current situation analysis of Devops and noops
Leverage Google cloud infrastructure and landing area to build enterprise level cloud native excellent operation capability
Data science [9]: SVD (2)
栈(线性结构)
Sentinel 阿里开源流量防护组件
稀疏数组(非线性结构)
sudo提权
Linked list (linear structure)
一起学习SQL中各种join以及它们的区别
LeetCode 90. 子集 II
随机推荐
BGP routing optimization rules and notification principles
深入学习JVM底层(二):HotSpot虚拟机对象
Learn about various joins in SQL and their differences
RestTemplate请求时设置请求头,请求参数,请求体。
CUDA中的Warp matrix functions
【张三学C语言之】—深入理解数据存储
浏览器原理思维导图
LeetCode 40. 组合总和 II
Arduino Wire 库使用
ShardingSphere-JDBC篇
The official zero foundation introduction jetpack compose Chinese course is coming!
The difference between session and cookies
Don't use the new WP collection. Don't use WordPress collection without update
Google Play Academy 组队 PK 赛,正式开赛!
Redis——大Key問題
Invalid operation: Load into table ‘sources_ orderdata‘ failed. Check ‘stl_ load_ errors‘ system table
CUDA中的异步数据拷贝
日志(常用的日志框架)
TensorRT的功能
一起学习SQL中各种join以及它们的区别