POST不同提交方式對應的Content-Type,及java伺服器接收引數方式
簡介:
Content-Type(MediaType),即是Internet Media Type,網際網路媒體型別;也叫做MIME型別,在Http協議訊息頭中,使用Content-Type來表示具體請求中的媒體型別資訊.參考
response.Header裡常見Content-Type一般有以下四種:
application/x-www-form-urlencoded
multipart/form-data
application/json
text/xml
詳解:
1.application/x-www-form-urlencoded
application/x-www-form-urlencoded是最常見的Content-Type,form表單預設提交方式對應的content-type.
當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>
後臺:
import java.io.Serializable;
public class Student implements Serializable {
private String name;
private String hobby;
private int age;
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-data
當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