通過Ajax進行POST提交JSON型別的資料到SpringMVC Controller的方法
阿新 • • 發佈:2019-01-24
現在在做的專案用到了SpringMVC框架,需要從前端angular接收請求的JSON資料,為了測試方便,所以直接先用AJAX進行測試,不過剛開始用平時用的ajax方法,提交請求會出現415或者400錯誤,經過研究,終於可以了,現在做個總結。
js程式碼:
[javascript] view plain copy- 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
- $.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);
- }
- publicclass Employee{
- public string FirstName { get; set; }
- public string LastName { get; set; }
- }
值得注意的有2點:
1)Ajax 選項中
[javascript] view plain copy- contentType: "application/json"
這一條必須寫,表明request的資料型別是json。
而
[javascript] view plain copy- dataType: "json"
這一條表示返回值的型別,不是必須的,且依據返回值型別而定。
2)選項中
[javascript] view plain copy- data: JSON.stringify({ 'foo': 'foovalue', 'bar': 'barvalue' })
很多時候我們將資料寫作: [javascript] view plain copy
- { 'foo': 'foovalue', 'bar': 'barvalue' }
這樣會導致錯誤,因為js會預設將這個json物件放到表單資料中,故而導致controller接收不到。
有兩種辦法處理:第一種方式是用JSON.stringify()函式,其中JSON被Ecmascript5定義為全域性物件。
第二種方式是直接用雙引號包裹起來,比如data: "{'str1':'foovalue', 'str2':'barvalue'}"。