我有以下看法上側JSON請求Spring mvc服務器。嘗試後JSON到控制器(服務器拒絕這個請求)
的index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" >
$(document).ready(function(){
sendAjax();
});
function sendAjax() {
$.ajax({
url: "/shop/main/order/model",
type: 'POST',
dataType: 'json',
data: " { \"totalPrice\": 10, \"custumerName\":\"vasiya\", \"ItemsList\": [ { \"id\": 1,\"name\":\"qqq\", \"price\": 10, \"count\": 2 } ] }",
contentType: 'application/json',
mimeType: 'application/json',
success: function(data) {
alert(data.totalPrice + " " + data.custumerName);
},
error:function(data,status,er) {
alert("error: "+data+" status: "+status+" er:"+er);
}
});
}
</script>
</body>
</html>
controller
看起來像這樣
@Controller
@RequestMapping("/order")
public class OrderController {
@RequestMapping(value="/model", method = RequestMethod.POST)
public @ResponseBody OrderModel post(@RequestBody final OrderModel model) {
System.out.println(model.getItemsList());
System.out.println(model.getTotalPrice());
return model;
}
}
}
OrderModel.java
public class OrderModel implements Serializable {
private static final long serialVersionUID = 1L;
String custumerName;
int totalPrice;
Items[] itemsList;
public void setTotalPrice(int totalPrice) {
this.totalPrice = totalPrice;
}
public void setItemsList(Items[] itemsList) {
this.itemsList = itemsList;
}
public int getTotalPrice() {
return totalPrice;
}
public Items[] getItemsList() {
return itemsList;
}
public void setCustumerName(String custumerName) {
this.custumerName = custumerName;
}
public String getCustumerName() {
return custumerName;
}
public OrderModel(String custumerName, int totalPrice, Items[] itemsList) {
this.custumerName = custumerName;
this.totalPrice = totalPrice;
this.itemsList = itemsList;
}
}
Items.java是一個簡單的POJO類,它是爲映射hibernate實體而設計的,它只包含String和long類型字段。
所以當我試圖訪問index.html
它不會發回任何迴應。在瀏覽器的控制檯我得到如下:
POST http://localhost:8080/shop/main/order/model 415()
HTTP狀態415 -
類型狀態報告
消息
介紹:服務器拒絕此請求,因爲請求實體 的格式不受請求的資源爲 請求的方法。
乍一看,我覺得有一點奇怪的\」請求體。試試這個數據:{totalPrice:10,custumerName:'vasiya',ItemsList:[{id:1,name:'qqq',price:10,count:2}]},' – MaVVamaldo
nope,問題仍然存在 – ketchyn
讓我指向你[這裏](http://stackoverflow.com/a/36084619/740480)。也許這是'@ RequestMapping'中缺少'consumes ='application/json'' – MaVVamaldo