POST不一樣提交方式對應的Content-Type,及java服務器接收參數方式

簡介:
Content-Type(MediaType),便是Internet Media Type,互聯網媒體類型;也叫作MIME類型,在Http協議消息頭中,使用Content-Type來表示具體請求中的媒體類型信息.參考前端

response.Header裏常見Content-Type通常有如下四種:java

application/x-www-form-urlencoded
multipart/form-data
application/json
text/xml
詳解:
1.application/x-www-form-urlencodedajax

application/x-www-form-urlencoded是最多見的Content-Type,form表單默認提交方式對應的content-type.json

當action爲get時候,瀏覽器用x-www-form-urlencoded的編碼方式把form數據轉換成一個字串(name1=value1&name2=value2...),而後把這個字串追加到url後面,用?分割,加載這個新的url.
當action爲post,且表單中沒有type=file類型的控件時,Content-Type也將採用此編碼方式,form數據將以key:value鍵值對的方式傳給server.後端

表單提交:瀏覽器

<form action="/test" method="post">
<input type="text" name="name" value="zhangsan"> 
<input type="text" name="age" value="12"> 
<input type="text" name="hobby" value="football">
  </form>

後臺:app

import java.io.Serializable;前後端分離

public class Student implements Serializable {
private String name;
private String hobby;
private int age;ide

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getHobby() {
    return hobby;
}

public void setHobby(String hobby) {
    this.hobby = hobby;
}

public int getAge() {
    return age;
}

public void setAge(int age) {
    this.age = age;
}

}
@RequestMapping(value = "/test", method = RequestMethod.POST)
public String test(Student student) {
System.out.println(student.getName());
return "/test1";
}
2.multipart/form-datapost

當post表單中有type=file控件時content-type會使用此編碼方式.

表單提交:

<form action="/test" method="post" enctype="multipart/form-data">
<input type="text" name="name" value="zhangsan"> 
<input type="text" name="age" value="12"> 
<input type="text" name="hobby" value="football">
<input type="file" name="file1"
  </form>

後臺:

@RequestMapping(value = "/test", method = RequestMethod.POST)
public String test(Student student,@RequestParam(value = "file1", required = false) MultipartFile file1) {
System.out.println(student.getName());
return "/test1";
}
3.application/json

隨着json規範的流行,以及先後端分離趨勢所致,該編碼方式被愈來愈多人接受.
先後端分離後,前端一般以json格式傳遞參數,所以該編碼方式較適合RestfulApi接口.

前端傳參:

$.ajax({
url: '/test',
type: 'POST',
data: {
"name": "zhangsan",
"age": 12,
"hobby": "football"
},
dataType: "json",
success: function (date) {

}
            })

後臺:

@RequestMapping(value = "/test", method = RequestMethod.POST)
public String test(@RequestBody Student student) {
System.out.println(student.getName());
return "/test1";
}
4.text/xml

XML-RPC(XML Remote Procedure Call)。它是一種使用 HTTP 做爲傳輸協議,XML 做爲編碼方式的遠程調用規範。

soapUI等xml-rpc請求的參數格式.

提交參數:

<arg0>
        <name>zhangsan</name>
        <age>12</age>
        <hobby>footbal</hobby>
     </arg0>

分類: java

相關文章
相關標籤/搜索