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>