【发布时间】:2016-05-13 13:09:09
【问题描述】:
我在视图端有以下 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 类,专为映射休眠实体而设计,仅包含 String 和 long 类型字段。
因此,当我尝试访问 index.html 时,它不会发回任何响应。在浏览器的控制台中,我得到以下信息:
POST http://localhost:8080/shop/main/order/model415 ()
HTTP 状态 415 -
输入状态报告
消息
描述:服务器拒绝了这个请求,因为请求实体 所请求的资源不支持的格式 请求的方法。
【问题讨论】:
-
乍一看,我发现请求正文中的那些\"有点奇怪。试试这个
data: { totalPrice: 10, custumerName:'vasiya', ItemsList: [ {id: 1,name:'qqq', price: 10, count: 2 } ] }, -
不,问题仍然存在
-
让我指点你here。也许是
@RequestMapping中缺少的consumes="application/json" -
是的,我已经注意到了,但还是不行
-
我尝试通过邮递员模仿同样的请求,得到同样的错误,看来是服务器端的问题
标签: ajax spring spring-mvc