前言
由于水平比较小白,对于传入的参数理解有些不太通透,因此总结一下,方便查阅
使用工具
idea,postman
具体代码
1 传一个参数
required = false
表示可以不传参数,不传参数时用null
代替,不是""
空字符串,要用name == null
判断,使用"".equals(name)
无效,使用name.equals("")
会报空指针异常。required 默认为 true
@RequestMapping("/getInfo")
public String getInfo(
@RequestParam(value = "userId", required = false) String userId){
String response = testFaceService.getInfo(userId);
return response;
}
2 传多个参数
@RequestMapping("/getInfo")
public String getInfo(
@RequestParam(value = "userId", required = false) String userId,
@RequestParam(value = "name", required = false) String name){
String response = testFaceService.getInfo(userId, name);
return response;
}
3 传json格式的字符串
将 json 格式的字符串转换成 map 集合
JsonUtil.parse()
方法的使用根据具体的工具类
@RequestMapping("/getInfo")
public String getInfo(@RequestParam String params) throws Exception{
Map<String, String> param = new HashMap<>();
if (!StringUtils.isEmpty(params)) {
param = JsonUtil.parse(params, Map.class);
}
String response = testFaceService.find(param);
return response;
}
4 传 map 集合
用 @RequestBody
@RequestMapping("/getInfo")
public String getInfo(@RequestBody Map<String, Object> map) throws Exception{
String userId = (String)map.get("userId");
return userId ;
}
//结果为 : 2
扫描二维码关注公众号,回复:
2547373 查看本文章
用 @RequestParam
@RequestMapping("/getInfo")
public String getInfo(@RequestParam Map<String, Object> map) throws Exception{
String params = (String) map.get("map");
JSONObject jsonObject = (JSONObject) JSON.parse(params );
return jsonObject .getString("userId");
}
//结果为:2
//传进去的是以map为键的集合,可以转换成json或怎样操作都可以: {map={"userId":"2"}}
`
5 传 文件
@RequestMapping(value = "/findByModel")
public String find(@RequestParam MultipartFile files) throws Exception{
//直接将文件上传至某地
files.transferTo(new File("E:\\test\\1.jpg"));
//可以获取文件的名字
files.getOriginalFilename();
}
有的将 Multipart 文件这么转成 File 文件
CommonsMultipartFile cf = (CommonsMultipartFile)files;
//这个myfile是MultipartFile的
DiskFileItem fi = (DiskFileItem) cf.getFileItem();
File file = fi.getStoreLocation();
String name = file.getName();
pom.xml
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>