欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

springmvc接口接收參數(shù)與請(qǐng)求參數(shù)格式的整理

 更新時(shí)間:2021年11月15日 11:29:30   作者:滴丶學(xué)生卡  
這篇文章主要介紹了springmvc接口接收參數(shù)與請(qǐng)求參數(shù)格式的整理,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

springmvc接口接收參數(shù)與請(qǐng)求參數(shù)格式

前言: 相信大家在剛開(kāi)始接觸接口定義與調(diào)用時(shí)遇到過(guò)接口接收不到請(qǐng)求參數(shù)的問(wèn)題,本人也一樣,使用springmvc去定義接口或調(diào)用第三方http接口時(shí)或多或少會(huì)搞混;下面咱們一起來(lái)整理下接口定義和請(qǐng)求參數(shù)格式的關(guān)系。

一、首先我們需要認(rèn)識(shí)下http請(qǐng)求中的Content-Type

我們常用的有以下幾種:

1、application/x-www-form-urlencoded; charset=UTF-8,瀏覽器的原生 form 表單,提交的數(shù)據(jù)按照 key1=val1&key2=val2 的方式進(jìn)行編碼,key和value都進(jìn)行了URL轉(zhuǎn)碼。

2、multipart/form-data:使用表單上傳文件時(shí),必須設(shè)置 form 的 enctyped 屬性。

3、application/json; charset=utf-8,請(qǐng)求參數(shù)是序列化后的json格式字符串,方便提交復(fù)雜結(jié)構(gòu)的數(shù)據(jù),特別適合RESTful 的接口。

二、注解@RequestParam(value=“id”)

1、常用來(lái)處理地址欄傳參和表單提交的參數(shù)綁定,Content-Type為application/x-www-form-urlencoded編碼的內(nèi)容,提交方式GET、POST

2、如果用java發(fā)送http請(qǐng)求,需采用key、value傳參方式發(fā)送數(shù)據(jù),如下寫(xiě)法:

    public static String post(HttpClient httpClient, String url, Map<String, String> params,
            Map<String, String> headers) throws ClientProtocolException, IOException {
        logger.info("Ready Post Request Url[{}]", url);
        HttpPost post = new HttpPost(url);
        setHttpHeaders(post, headers);
        List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            nameValuePairList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nameValuePairList, Consts.UTF_8);
        post.setEntity(entity);
        HttpResponse response = httpClient.execute(post);
        if (null == response || response.getStatusLine() == null) {
            logger.info("Post Request For Url[{}] is not ok. Response is null", url);
            return null;
        } else if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            logger.info("Post Request For Url[{}] is not ok. Response Status Code is {}", url,
                    response.getStatusLine().getStatusCode());
            return null;
        }
        return EntityUtils.toString(response.getEntity());
    }

三、注解@RequestBody

1、一般用來(lái)接收json格式數(shù)據(jù),后端直接定義好請(qǐng)求參數(shù)的bean,Content-Type為application/json; charset=utf-8,使用示例:

@RequestBody User user

請(qǐng)求參數(shù):

{
    "id": 1,
    "userName": "bryant",
    "password": "123456",
    "name": "kobe",
    "Date": "1990-02-27"
}

2、使用java發(fā)送請(qǐng)求代碼示例:

    public static String post(HttpClient httpClient, String url, String content, Map<String, String> headers)
            throws ClientProtocolException, IOException {
        logger.info("Ready Post Request Url[{}]", url);
        url = url.replaceAll(" ", "%20");
        HttpPost post = new HttpPost(url);
        setHttpHeaders(post, headers);
        StringEntity entity = new StringEntity(content, Constants.CHARSET_UTF8);
        post.setEntity(entity);
        HttpResponse response = httpClient.execute(post);
        if (null == response || response.getStatusLine() == null) {
            logger.info("Post Request For Url[{}] is not ok. Response is null", url);
            return null;
        } else if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            logger.info("Post Request For Url[{}] is not ok. Response Status Code is {}", url,
                    response.getStatusLine().getStatusCode());
            return null;
        }
        return EntityUtils.toString(response.getEntity(), "utf-8");
    }
    public static void main(String[] args) throws IOException {
        Map<String, Object> map = new HashMap<>();
        map.put("empId", "1");
        map.put("empName", "測(cè)試用戶");
        map.put("empEmail", "test@qq.com");
        Map<String, String> head = new HashMap<>();
        // 一定要設(shè)置參數(shù)格式
        head.put("Content-Type", "application/json;charset=UTF-8");
        System.out.println(HttpCaller.post(HttpClients.createDefault(), "http://localhost:8080/user/add",
                JsonUtil.toJson(map), head));
    }

3、如果使用postman調(diào)試接口,需要設(shè)置傳參方式為raw-JSON,如下圖:

在這里插入圖片描述

springmvc接口接受前端傳遞參數(shù)數(shù)據(jù)類型總結(jié)

一、springMVC中controller參數(shù)是自動(dòng)注入

在springMVC中,controller中方法的參數(shù)是自動(dòng)注入的,在使用注解的方式下,通常有:

  • @RequestParam:取querystring當(dāng)中的參數(shù)
  • @PathVariable:取 在@RequestMapping中定義的占位符中的參數(shù)(/test/{id})
  • @RequestBody:取request 這個(gè)消息體 (可以組裝json對(duì)象)

在不使用注解的情況下,默認(rèn)有一些對(duì)象可以自動(dòng)注入如:

  • HttpServletRequest
  • HttpServletResponse
  • MultipartFile
  • MultipartRequest

除此之外不使用注解的情況下,也可以接受前臺(tái)傳入的querystring中的參數(shù)。

二、 接受前端傳遞的對(duì)象

1、從querystring中的參數(shù)中獲取

@RequestParam:接受對(duì)象類型(Integer、String、Boolean等基本數(shù)據(jù)類型),不能接收自定義類型。

不帶注解:接受基本數(shù)據(jù)類型,若接收類型為自定義類型,會(huì)組裝參數(shù)中與自定義類型屬性名和類型相符的參數(shù)。

這種方式總結(jié):

(1).獲取自定義類型的對(duì)象時(shí),不使用注解即可以獲取

(2).在組裝對(duì)象時(shí)可以使用以被獲取過(guò)的參數(shù)

注意:$.ajax contenType是appliation/json的時(shí)候,在后臺(tái)用spring mvc的@Requestparam注解接收參數(shù),始終接收不到。因?yàn)锧RequestParam 底層是通過(guò)request.getParameter方式獲得參數(shù)的,也就是說(shuō),@RequestParam 和 request.getParameter是同一回事。

所以@RequestParam可以處理get 方式中queryString的值,也可以處理post方式中 body data的值。@RequestParam用來(lái)處理Content-Type: 為 application/x-www-form-urlencoded編碼的內(nèi)容(及表單內(nèi)容數(shù)據(jù)),提交方式GET、POST。

2、從請(qǐng)求體(body)中獲?。矮@取對(duì)象數(shù)據(jù))

當(dāng)請(qǐng)求體中是一段json數(shù)據(jù)時(shí),@RequestBody會(huì)解析該json字符串并將其注入指定的自定義類型中。

通過(guò)@RequestBody的方式可以接收以json數(shù)據(jù)傳輸?shù)膶?duì)象,但前提是請(qǐng)求的Content-Type必須為application/json,并且引入了jackson-databind包

注意:

1.@RequestBody該注解常用來(lái)處理Content-Type: 不是application/x-www-form-urlencoded編碼的內(nèi)容,例如application/json, application/xml等;

2.@RequestBody接收的是一個(gè)Json對(duì)象的字符串,而不是一個(gè)Json對(duì)象。在ajax請(qǐng)求往往傳的都是Json對(duì)象,用 JSON.stringify(data)的方式就能將對(duì)象變成字符串。

3.不使用@RequestBody注解時(shí),可以接收Content-Type為application/x-www-form-urlencoded類型的請(qǐng)求所提交的數(shù)據(jù),數(shù)據(jù)格式:aaa=111b b b = 222 。 f o r m 表 單 提 交 以 及 j Q u e r y 的 bbb=222。form表單提交以及jQuery的bbb=222。form表單提交以及jQuery的.post()方法所發(fā)送的請(qǐng)求就是這種類型。例如后臺(tái)接口接收數(shù)據(jù)的對(duì)象前不加@RequestBody修飾。

3、接收前端傳遞的數(shù)組

接收數(shù)組可以使用注解方式的@RequestParam、@RequestBody或者無(wú)注解的方式,也可以同時(shí)使用他們?nèi)齻€(gè)

在接受數(shù)組時(shí),默認(rèn)按照方法的參數(shù)名來(lái)映射請(qǐng)求的參數(shù),目前很多前端框架喜歡傳遞數(shù)組時(shí)在請(qǐng)求參數(shù)后面加上"[]",所以使用@RequestParam時(shí)可以規(guī)定value使之對(duì)應(yīng)如@RequestParam(“ids[]”) Integer[] ids。

三、小結(jié)一下

由上可知道,后臺(tái)需要處理什么數(shù)據(jù),或者需要前臺(tái)需要傳遞什么類型的數(shù)據(jù)時(shí),我們既可以根據(jù)這些特性來(lái)判斷,而不會(huì)導(dǎo)致有時(shí)contentType不一致,甚至不知道自己需要前端傳什么樣類型的數(shù)據(jù)格式等等。

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論