一、前言
在Web开发中我们需要和前端进行数据的交互,这个时候就需要获取前端传入的数据,我们一般有如下几种方式进行数据的交互:@PathVariable、@RequestParam和@RequestBody。
二、@RequestParam
获取传输过来的参数。
举例:使用@RequestParam获取不同类型的参数
package com.example.hellodemo.controller;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;
/**
* @author qx
* @date 2023/11/30
* @des
*/
@RestController
public class DbController {
@PostMapping("/test")
public Map<String, Object> testDemo(@RequestParam String name, @RequestParam Integer age) {
Map<String, Object> map = new HashMap<>();
map.put("name", name);
map.put("age", age);
return map;
}
}
测试:
使用Postman中的Params方式进行传参。
使用Postman中的form-data方式进行传参。
使用Postman中的application/x-www-form-urlencoded方式进行传参。
三、@RequestBody
@RequestBody注解一般主要是用来处理"application/json或"application/xml"两种请求数据,当前端或者第三方请求传入JSON数据过来的时候,我们使用这个注解就可以把传入的字段或属性将你创建的实体类绑定在一起。还有也可以使用Map进行接收。
1.使用实体类接收
package com.example.hellodemo.bean.one;
import lombok.Data;
/**
* @author qx
* @date 2023/11/30
* @des
*/
@Data
public class DbOneEntity {
private Long id;
private String name;
}
package com.example.hellodemo.controller;
import com.example.hellodemo.bean.one.DbOneEntity;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;
/**
* @author qx
* @date 2023/11/30
* @des
*/
@RestController
public class DbController {
@PostMapping("/test")
public Map<String, Object> testDemo(@RequestBody DbOneEntity dbOneEntity) {
Map<String, Object> map = new HashMap<>();
map.put("name", dbOneEntity.getName());
map.put("id", dbOneEntity.getId());
return map;
}
}
测试:
2.使用map接收
当前端或者第三方给你参数与你自己对应的实体不相符合的时候,我们需要使用Map去接收。
package com.example.hellodemo.controller;
import com.example.hellodemo.bean.one.DbOneEntity;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;
/**
* @author qx
* @date 2023/11/30
* @des
*/
@RestController
public class DbController {
@PostMapping("/test")
public Map<String, Object> testDemo(@RequestBody Map<String, Object> map) {
Map<String, Object> hashMap = new HashMap<>();
hashMap.put("name", map.get("name"));
hashMap.put("id", map.get("id"));
hashMap.put("age", map.get("age"));
return hashMap;
}
}
测试:
四、@PathVariable
用于获取请求路径上的变量,代码示例如下:
package com.example.hellodemo.controller;
import com.example.hellodemo.bean.one.DbOneEntity;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;
/**
* @author qx
* @date 2023/11/30
* @des
*/
@RestController
public class DbController {
@PostMapping("/test/{name}/{id}")
public Map<String, Object> testDemo(@PathVariable("name") String name, @PathVariable("id") Integer id) {
Map<String, Object> hashMap = new HashMap<>();
hashMap.put("name", name);
hashMap.put("id", id);
return hashMap;
}
}
测试: