@RequestBody和@RequestParam注解使用

@RequestBody注解使用

文章参考:https://blog.csdn.net/justry_deng/article/details/80972817
写的很详细,我只是看了部分.

用法

@RequestBody主要用来接收前端传递给后端的json字符串中的数据的(请求体中的数据的);GET方式无请求体,所以使用@RequestBody接收数据时,前端不能使用GET方式提交数据,而是用POST方式进行提交。
在后端的同一个接收方法里,@RequestBody与@RequestParam()可以同时使用,@RequestBody最多只能有一个,用来接收请求体中的json字符串,而@RequestParam()可以有多个,用于接收url中的k-v参数的传递。

测试代码

同时使用@RequestBody和@RequestParam注解分别接收请求体中的json和url中的k-v数据.

@Controller
public class TestController {
    @RequestMapping("/test")
    @ResponseBody
    public Object test(@RequestBody Map requestParam,
                       @RequestParam String phone,//接收url传参
                       @RequestParam String address
                       ) {
        //接收请求体中的json数据
        String name = (String)requestParam.get("name");
        Integer age = (Integer)requestParam.get("age");

        //返回数据
        List list = new ArrayList<>();
        list.add("@RequestBody==="+name);
        list.add("@RequestBody==="+age);
        list.add("@RequestParam======"+phone);
        list.add("@RequestParam======"+address);

        return list;
    }
}
 
  

数据测试

@RequestBody和@RequestParam注解使用_第1张图片
同时有两种传递参数的方式.
返回如下:
@RequestBody和@RequestParam注解使用_第2张图片

另外说明

@RequestParam也可以接受多个数据使用map进行封装,这样有利于接口的参数的扩展

	@ResponseBody
    @RequestMapping(value = "/createHqlSelectDisk", method = {RequestMethod.POST}, produces = {MediaType.APPLICATION_JSON_VALUE})
    public String createHqlSelectDisk(@RequestParam Map parMap) {
        //取出相关信息
        String erp = WebUtil.getLoginUser();
        String hql = (String) parMap.get("sql");
        String queryId = (String) parMap.get("queryId");
        String dataSource = (String) parMap.get("dataSource");
        String disk = ((String) parMap.get("selectDisk")).toLowerCase();
        
        return "test";
    }

你可能感兴趣的:(java,springboot,注解学习)