SpringBoot中使用注解@RequestParam与 @RequestBody区别

在SpringBoot项目中,通查使用 @RequestParam和 @RequestBody解析http请求中的参数,二者在使用上有所区别。

1、@RequestParam 注解解析GET请求参数

先定义一个controller,并规定传入name和id两个参数,请求方式为get,分别打印出参数url,查询字符串参数、编码方式、请求方式。

@GetMapping("/test")
    public String test (@RequestParam("name") String name, @RequestParam("id") int id, HttpServletRequest httpServletRequest) {
        logger.info("请求url {}", httpServletRequest.getRequestURI());
        logger.info("查询字符串参数 {}",httpServletRequest.getQueryString());
        logger.info("参数编码方式 {}", httpServletRequest.getContentType());
        logger.info("请求方式 {}", httpServletRequest.getMethod());
        logger.info("name {}",name);
        logger.info("id {}",id);
        return "ok";
    }

使用postman请求,分别使用查询字符串、放入body的form-data和x-www-form-urlencoded 格式进行请求:

 

   

 使用查询字符串、form-data 的参数均能正确解析, 但无法解析get请求的  x-www-form-urlencoded 参数格式。

2、@RequestParam 注解解析POST请求参数

重新定义一个controller。

@PostMapping("text")
    public String text(@RequestParam("name") String name, @RequestParam("id") int id, HttpServletRequest httpServletRequest) {
        logger.info("请求url {}", httpServletRequest.getRequestURI());
        logger.info("查询字符串参数 {}",httpServletRequest.getQueryString());
        logger.info("参数编码方式 {}", httpServletRequest.getContentType());
        logger.info("请求方式 {}", httpServletRequest.getMethod());
        logger.info("name {}",name);
        logger.info("id {}",id);
        return "ok";
    }

依次使用查询字符串、放入body使用form-data格式、和 x-www-form-urlencoded参数格式请求。

 

   

可以看到使用@RequestParam注解均能解析参数。

3、@RequestBody 注解解析参数

 @RequestBody注解可以解析 body体的 application/json编码方式的请求参数GET、POST方式均可以解析。

    @GetMapping("signGet")
    public String signin(@RequestBody User user, HttpServletRequest httpServletRequest) {
        logger.info("请求url {}", httpServletRequest.getRequestURI());
        logger.info("查询字符串参数 {}",httpServletRequest.getQueryString());
        logger.info("参数编码方式 {}", httpServletRequest.getContentType());
        logger.info("请求方式 {}", httpServletRequest.getMethod());
        logger.info("name {}",user.name);
        logger.info("id {}",user.id);
        return "ok";
    }

    @PostMapping("signPost")
    public String signout(@RequestBody User user, HttpServletRequest httpServletRequest) {
        logger.info("请求url {}", httpServletRequest.getRequestURI());
        logger.info("查询字符串参数 {}",httpServletRequest.getQueryString());
        logger.info("参数编码方式 {}", httpServletRequest.getContentType());
        logger.info("请求方式 {}", httpServletRequest.getMethod());
        logger.info("name {}",user.name);
        logger.info("id {}",user.id);
        return "ok";
    }

 

  

 由于springboot内置了Jackson,自动将参数解析并组装到实体类里面。以上结果运行在spring boot 2.7 并使用spring boot默认配置测试。

有关get请求是否可以有body体的问题,可以参阅 HTTP GET 请求可以有 body 吗?

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章