現在在做的項目用到了SpringMVC框架,需要從前端angular接收請求的JSON數據,為了測試方便,所以直接先用AJAX進行測試,不過剛開始用平時用的ajax方法,提交請求會出現415或者400錯誤,經過研究,終於可以了,現在做個總結。
js代碼:
-
function postSimpleData() {
-
$.ajax({
-
type:
"POST",
-
url:
"Service/SimpleData",
-
contentType:
"application/json",
//必須有
-
dataType:
"json",
//表示返回值類型,不必須
-
data:
JSON.stringify({
'foo':
'foovalue',
'bar':
'barvalue' }),
//相當於 //data: "{'str1':'foovalue', 'str2':'barvalue'}",
-
success:
function (jsonResult) {
-
alert(jsonResult);
-
}
-
});
-
}
-
function login(){
-
$.ajax({
-
url:
"Service/login",
-
type:
"POST",
-
contentType:
"application/json",
-
dataType:
"json",
-
data:
JSON.stringify({
-
MachineIP:
"127.0.0.1",
-
AppTag:
"4",
-
RequestInfo:{
-
StaffCode:
"",
-
Password:
"",
-
StaffCard:
"01411"
-
},
-
}),
-
async:
true,
-
success:
function(data) {
-
var ss =
JSON.stringify(data);
-
$(
"#result").val(ss);
-
console.log(ss);
-
}
-
});
-
}
-
function postEmployees() {
-
$.ajax({
-
type:
"POST",
-
url:
"Service/Employees",
-
contentType:
"application/json",
-
dataType:
"json",
-
data:
JSON.stringify({
"Employees": [
-
{
"firstName":
"Bill",
"lastName":
"Gates" },
-
{
"firstName":
"George",
"lastName":
"Bush" },
-
{
"firstName":
"Thomas",
"lastName":
"Carter" }
-
]
-
-
}),
-
success:
function (jsonResult) {
-
alert(jsonResult);
-
}
-
});
-
}
JAVA Controller代碼:
-
@RequestMapping(value =
"/SimpleData", method = RequestMethod.POST)
-
@ResponseBody
-
public ActionResult SimpleData(string foo, string bar) {
-
return Json(
"SimpleData", JsonRequestBehavior.AllowGet);
-
}
-
-
@RequestMapping(value =
"/login", method = RequestMethod.POST)
-
@ResponseBody
-
public ResponseProtocolMap login(@RequestBody JSONObject requestJson, HttpServletRequest request) {
-
ResponseProtocolMap responseProtocolMap =
null;
-
String machineIP = RequestJsonUtils.getMachineIP(requestJson);
-
String appTag = RequestJsonUtils.getAppTag(requestJson);
-
JSONObject requestInfo = RequestJsonUtils.getRequestInfo(requestJson);
-
if (requestInfo ==
null) {
-
responseProtocolMap =
new ResponseProtocolMap(
"-1",
"參數錯誤");
-
}
else {
-
String staffCode = RequestJsonUtils.getValueByKey(requestInfo,
"StaffCode");
-
String password = RequestJsonUtils.getValueByKey(requestInfo,
"Password");
-
String staffCard = RequestJsonUtils.getValueByKey(requestInfo,
"StaffCard");
-
responseProtocolMap = sysLoginService.login(staffCode, password, staffCard, appTag, request);
-
}
-
return responseProtocolMap;
-
}
-
-
@RequestMapping(value =
"/Employees", method = RequestMethod.POST)
-
@ResponseBody
-
public ActionResult Employees(List<Employee> Employees) {
-
return Json(
"Employees", JsonRequestBehavior.AllowGet);
-
}
-
public
class Employee{
-
public string FirstName { get; set; }
-
public string LastName { get; set; }
-
}
值得注意的有2點:
1)Ajax 選項中
contentType: "application/json"
這一條必須寫,表明request的數據類型是json。
而
dataType: "json"
這一條表示返回值的類型,不是必須的,且依據返回值類型而定。
2)選項中
data: JSON.stringify({ 'foo': 'foovalue', 'bar': 'barvalue' })
很多時候我們將數據寫作:
{ 'foo': 'foovalue', 'bar': 'barvalue' }
這樣會導致錯誤,因為js會默認將這個json對象放到表單數據中,故而導致controller接收不到。
有兩種辦法處理:第一種方式是用JSON.stringify()函數,其中JSON被Ecmascript5定義為全局對象。
第二種方式是直接用雙引號包裹起來,比如data: "{'str1':'foovalue', 'str2':'barvalue'}"。