现在在做的项目用到了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'}"。

通过Ajax进行POST提交JSON类型的数据到SpringMVC Controller的方法的更多相关文章

  1. springmvc接收JSON类型的数据

    1.在使用AJAX传递JSON数据的时候要将contentType的类型设置为"application/json",否则的话会提示415错误 2.传递的data需要时JSON类型的 ...

  2. springMVC参数绑定JSON类型的数据

    需求就是: 现在保存一个Student,并且保存Student的friend,一个student会有多个朋友,这里要传递到后台的参数是: var friends = new Array(); var ...

  3. 关于ajax 进行post提交 json数据到controller

    首选需要参考的两个博客: www.cnblogs.com/Benjamin/archive/2013/09/11/3314576.html http://www.cnblogs.com/quanyon ...

  4. 通过Ajax post Json类型的数据到Controller

    View function postSimpleData() { $.ajax({ type: "POST", url: "/Service/SimpleData&quo ...

  5. jquery ajax提交json格式的数据,后台接收并显示各个属性

    我的表单如下: <form onsubmit="return false"> <ul> <li><span>用户名</span ...

  6. Mysql里查询字段为Json格式的数据模糊查询以及分页方法

    public void datagrid(CustomFormEntity customForm,HttpServletRequest request, HttpServletResponse res ...

  7. 9.SpringMVC和json结合传递数据 && 10.SpringMVC获取controller中json的数据

  8. SpringMVC——对Ajax的处理(包含 JSON 类型)

    一.首先要搞明白的一些事情. 1.从客户端来看,需要搞明白: (1)要发送什么样格式的 JSON 数据才能被服务器端的 SpringMVC 很便捷的处理,怎么才能让我们写更少的代码,如何做好 JSON ...

  9. Struts2+Jquery实现ajax并返回json类型数据

    来源于:http://my.oschina.net/simpleton/blog/139212 摘要 主要实现步骤如下: 1.JSP页面使用脚本代码执行ajax请求 2.Action中查询出需要返回的 ...

随机推荐

  1. C++ new 的用法

    原文链接:http://www.builder.com.cn/2008/0104/696370.shtml “new”是C++的一个关键字,同时也是操作符.关于new的话题非常多,因为它确实比较复杂, ...

  2. 在navicat中如何新建连接数据库

    前几天给大家分享了如何安装Navicat,没有来得及上车的小伙伴可以戳这篇文章:手把手教你安装Navicat——靠谱的Navicat安装教程.今天给大家分享一下Navicat的简单使用教程,具体的教程 ...

  3. Flex XML/XMLList 常用操作

    1       XML.XMLList操作 Flex对xml提供了很多强大而灵活的操作.相对于其他语言,flex对xml的格式要求不那么苛刻,只要符合基本格式语法的字符串,flex能非常简单的转换成x ...

  4. 变量对象、作用域链和This

    变量对象 作用域链 This 整理自:https://www.cnblogs.com/TomXu/archive/2011/12/15/2288411.html 系列文章中变量对象,作用域链和this ...

  5. 【Henu ACM Round #13 A】 Hulk

    [链接] 我是链接,点我呀:) [题意] 在这里输入题意 [题解] 模拟. [代码] #include <bits/stdc++.h> using namespace std; int m ...

  6. HDU 3911 Black And White

    Black And White Time Limit: 3000ms Memory Limit: 32768KB This problem will be judged on HDU. Origina ...

  7. EditPlus,UltraEdit等编辑器列选择的方法

    在使用富文本编辑器的时候,通常模式是行选择状态,由于今天想使用EditPlus列选择状态, 于是通过在网上收集的资料,总结出相关富文本编辑器的列选择的方法. EditPlus  1)菜单:编辑 -&g ...

  8. 关于getinstalledpackages參数的分析。

    此blog不写API的使用方法仅仅分析此參数的知识点. 今天学习安卓突然学习到了getinstalledpackages()的方法获取到安装应用信息 ,他接收一个int flags的值.然后在网上查询 ...

  9. 黑马程序猿——JAVA面向对象的特性:封装,继承,多态

                                           - ----------android培训.java培训.java学习型技术博客.期待与您交流!------------  ...

  10. 74.QT窗口实现类的封装

    #include "mainwindow.h" #include <QApplication> #include <windows.h> //定义一个窗口类 ...