zoukankan      html  css  js  c++  java
  • 通过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'}"。


  • 相关阅读:
    ASP.NET验证控件的使用 拓荒者
    读书笔记:MFC单文档应用程序结构分析 拓荒者
    MFC单文档(SDI)全屏程序的实现 拓荒者
    jQuery的animate函数
    设备尺寸杂谈:响应性Web设计中的尺寸问题
    Yeoman学习与实践笔记
    IE对文档的解析模式及兼容性问题
    推荐给开发和设计人员的iPad应用
    几个移动应用统计平台
    颜色、网页颜色与网页安全色
  • 原文地址:https://www.cnblogs.com/jpfss/p/9318704.html
Copyright © 2011-2022 走看看