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 嗎?

 

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