通過Ajax進行POST提交JSON類型的數據到SpringMVC Controller的方法


現在在做的項目用到了SpringMVC框架,需要從前端angular接收請求的JSON數據,為了測試方便,所以直接先用AJAX進行測試,不過剛開始用平時用的ajax方法,提交請求會出現415或者400錯誤,經過研究,終於可以了,現在做個總結。

js代碼:


   
   
  
  
          
  1. function postSimpleData() {
  2. $.ajax({
  3. type: "POST",
  4. url: "Service/SimpleData",
  5. contentType: "application/json", //必須有
  6. dataType: "json", //表示返回值類型,不必須
  7. data: JSON.stringify({ 'foo': 'foovalue', 'bar': 'barvalue' }), //相當於 //data: "{'str1':'foovalue', 'str2':'barvalue'}",
  8. success: function (jsonResult) {
  9. alert(jsonResult);
  10. }
  11. });
  12. }
  13. function login(){
  14. $.ajax({
  15. url: "Service/login",
  16. type: "POST",
  17. contentType: "application/json",
  18. dataType: "json",
  19. data: JSON.stringify({
  20. MachineIP: "127.0.0.1",
  21. AppTag: "4",
  22. RequestInfo:{
  23. StaffCode: "",
  24. Password: "",
  25. StaffCard: "01411"
  26. },
  27. }),
  28. async: true,
  29. success: function(data) {
  30. var ss = JSON.stringify(data);
  31. $( "#result").val(ss);
  32. console.log(ss);
  33. }
  34. });
  35. }
  36. function postEmployees() {
  37. $.ajax({
  38. type: "POST",
  39. url: "Service/Employees",
  40. contentType: "application/json",
  41. dataType: "json",
  42. data: JSON.stringify({ "Employees": [
  43. { "firstName": "Bill", "lastName": "Gates" },
  44. { "firstName": "George", "lastName": "Bush" },
  45. { "firstName": "Thomas", "lastName": "Carter" }
  46. ]
  47. }),
  48. success: function (jsonResult) {
  49. alert(jsonResult);
  50. }
  51. });
  52. }

JAVA  Controller代碼:


   
   
  
  
          
  1. @RequestMapping(value = "/SimpleData", method = RequestMethod.POST)
  2. @ResponseBody
  3. public ActionResult SimpleData(string foo, string bar) {
  4. return Json( "SimpleData", JsonRequestBehavior.AllowGet);
  5. }
  6. @RequestMapping(value = "/login", method = RequestMethod.POST)
  7. @ResponseBody
  8. public ResponseProtocolMap login(@RequestBody JSONObject requestJson, HttpServletRequest request) {
  9. ResponseProtocolMap responseProtocolMap = null;
  10. String machineIP = RequestJsonUtils.getMachineIP(requestJson);
  11. String appTag = RequestJsonUtils.getAppTag(requestJson);
  12. JSONObject requestInfo = RequestJsonUtils.getRequestInfo(requestJson);
  13. if (requestInfo == null) {
  14. responseProtocolMap = new ResponseProtocolMap( "-1", "參數錯誤");
  15. } else {
  16. String staffCode = RequestJsonUtils.getValueByKey(requestInfo, "StaffCode");
  17. String password = RequestJsonUtils.getValueByKey(requestInfo, "Password");
  18. String staffCard = RequestJsonUtils.getValueByKey(requestInfo, "StaffCard");
  19. responseProtocolMap = sysLoginService.login(staffCode, password, staffCard, appTag, request);
  20. }
  21. return responseProtocolMap;
  22. }
  23. @RequestMapping(value = "/Employees", method = RequestMethod.POST)
  24. @ResponseBody
  25. public ActionResult Employees(List<Employee> Employees) {
  26. return Json( "Employees", JsonRequestBehavior.AllowGet);
  27. }


   
   
  
  
          
  1. public class Employee{
  2. public string FirstName { get; set; }
  3. public string LastName { get; set; }
  4. }

值得注意的有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'}"。



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM