jar包(Maven仓库):

Spring4 jar包(Maven仓库):

在测试过程中我查看了网上的一些教程,但是那些教程都是在Spring3环境下的,Spring3和Spring4解析json需要的jar文件不同.

在这里贴出Sring3解析json需要的jar

Sring3解析json需要的jar

1,页面获取后端数据

 jQuery.ajax( {
type : "GET",
contentType : "application/json",
url : "<%=request.getContextPath()%>/easyui/list.do",
dataType : "json",
success : function(data) {
if (data && data.success == "true") {
$("#info").html("共" + data.total + "条数据。<br/>");
$.each(data.data, function(i, item) {
$("#info").append(
"编号:" + item.id + ",姓名:" + item.username
+ ",年龄:" + item.age);
});
}
},
error : function() {
alert("error")
}
});

jqunery ajax get 向controller请求数据contentType : "application/json",  json格式,url为请求的地址,请求成功之后json数据添加到页面

@RequestMapping(value = "/list", method = RequestMethod.GET,consumes="application/json")
@ResponseBody
public Map<String, Object> getUserList() {
List<UserModel> list = new ArrayList<UserModel>();
UserModel um = new UserModel();
um.setId("1");
um.setUsername("sss");
um.setAge(222);
list.add(um);
Map<String, Object> modelMap = new HashMap<String, Object>(3);
modelMap.put("total", "1");
modelMap.put("data", list);
modelMap.put("success", "true"); return modelMap;
}
@ResponseBody   表示自动将页面json数据封装进对象只在contentType : "application/json",情况下允许.

2.向后端发送页面数据

//将一个表单的数据返回成JSON字符串
$.fn.serializeObject = function() {
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [ o[this.name] ];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
$("#submit").click(function() {
var jsonuserinfo = $.toJSON($("#form").serializeObject()); //$.toJSON($("#form")是 jqunery.json.js中的方法
alert(jsonuserinfo); jQuery.ajax( { type : "POST", //contentType: "application/json; charset=utf-8",  contentType : 'application/json', url : "<%=request.getContextPath()%>/easyui/add.do", data : jsonuserinfo, dataType : "json", success : function(data) { alert("新增成功!"); }, error : function(data) { alert("error") } }); });
serializeObject()方法将表单内容转换成json字符串,jqunery的json对象和json字符串之间的转换也许需要jqunery插件包

jquery.json-2.2.min.js   jquery提供的json包
json2.js      json官网提供的json包

var obj = JSON.parse(jsonuserinfo); //字符串转json对象,json2.js中的方法

var c = JSON.stringify(obj); //json对象转字json符串,json2.js中的方法

json对象和字符串的转换有很多种方式,具体的可以看其他的教程.

@RequestMapping(value = "/add", method = RequestMethod.POST,consumes="application/json")
@ResponseBody
public Map<String, String> addUser(@RequestBody UserModel model) {
//System.out.println(123);
int s = model.getAge();
String ss = model.getId();
String sss = model.getUsername();
TestUtil.test(s+ss+sss); Map<String, String> map = new HashMap<String, String>(1);
map.put("success", "true");
return map;
}
 @ResponseBody会自动将页面发送的json字符串解析成java对象,其实json对象底层就是map集合对象,java提供了工具可以将map集合转换成json对象,当然json对象和json数组的概念还是需要大家花费一些时间理解的

以下是全部代码:
<%@ page contentType="text/html; charset=utf-8" language="java" import="java.util.*,java.sql.*" errorPage="" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<base href="<%=basePath%>"> <title>Spring MVC</title>
<script src="${pageContext.request.contextPath}/static/editormd/examples/js/jquery.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/static/js/jquery.json-2.2.min.js"></script>
<script type="text/javascript">
//将一个表单的数据返回成JSON对象
$.fn.serializeObject = function() {
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [ o[this.name] ];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
}; $(document).ready(function() {
jQuery.ajax( {
type : "GET",
contentType : "application/json",
url : "<%=request.getContextPath()%>/easyui/list.do",
dataType : "json",
success : function(data) {
if (data && data.success == "true") {
$("#info").html("共" + data.total + "条数据。<br/>");
$.each(data.data, function(i, item) {
$("#info").append(
"编号:" + item.id + ",姓名:" + item.username
+ ",年龄:" + item.age);
});
}
},
error : function() {
alert("error")
}
});
$("#submit").click(function() {
var jsonuserinfo = $.toJSON($("#form").serializeObject());
alert(typeof jsonuserinfo);
jQuery.ajax( {
type : "POST",
//contentType: "application/json; charset=utf-8",
contentType : 'application/json', url : "<%=request.getContextPath()%>/easyui/add.do",
data : jsonuserinfo,
dataType : "json",
success : function(data) {
alert("新增成功!");
},
error : function(data) {
alert("error")
}
});
});
});
</script>
</head>
<body>
<div id="info"></div>
<form action="<%=request.getContextPath()%>/easyui/add.do" method="post" id="form">
编号:<input type="text" name="id" value="12"/>
姓名:<input type="text" name="username" value="走走走"/>
年龄:<input type="text" name="age" value="44"/> <input type="button" value="提交" id="submit"/>
</form>
</body>
</html>

HTML代码

/**
*
* Spring4 json test start -------------------------------
* @return
*/
@RequestMapping(value = "/list", method = RequestMethod.GET,consumes="application/json")
@ResponseBody
public Map<String, Object> getUserList() {
TestUtil.test("123"); List<UserModel> list = new ArrayList<UserModel>();
UserModel um = new UserModel();
um.setId("1");
um.setUsername("sss");
um.setAge(222);
list.add(um);
Map<String, Object> modelMap = new HashMap<String, Object>(3);
modelMap.put("total", "1");
modelMap.put("data", list);
modelMap.put("success", "true"); return modelMap;
} /**
* Spring4 json test
* @return
*/
@RequestMapping(value = "/add", method = RequestMethod.POST,consumes="application/json")
@ResponseBody
public Map<String, String> addUser(@RequestBody UserModel model) {
//System.out.println(123);
int s = model.getAge();
String ss = model.getId();
String sss = model.getUsername();
TestUtil.test(s+ss+sss); Map<String, String> map = new HashMap<String, String>(1);
map.put("success", "true");
return map;
}

Java代码

package com.zlay.pojo;

public class UserModel{
/**
*
* Spring4 json test class
* @return
*/
private String id;
private String username;
private int age ;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
} }

UserModel类

 

(Spring4 json入门)Spring4+SpringMVC+页面数据发送与接收(json格式)的更多相关文章

  1. ASP.NET POST XML JSON数据,发送与接收

    接收端通过Request.InputStream读取:byte[] byts = new byte[Request.InputStream.Length];Request.InputStream.Re ...

  2. [java,2018-01-16] HttpClient发送、接收 json 请求

    最近需要用到许多在后台发送http请求的功能,可能需要发送json和xml类型的数据. 就抽取出来写了一个帮助类: 首先判断发送的数据类型是json还是xml: import org.dom4j.Do ...

  3. 使用httperrequest,模拟发送及接收Json请求

    使用httpreques\Json-Handle\tcpdump\wireshark工具进行,抓取手机访问网络的包,分析request及response请求,通过httprequester来实现模拟发 ...

  4. 使用firefox插件httperrequest,模拟发送及接收Json请求 【转】

    转自[http://blog.csdn.net/feixue1232/article/details/8535212] 目标:使用httpreques\Json-Handle\tcpdump\wire ...

  5. L2CAP数据发送和接收

    ACL 链路在 Bluetooth 中非常重要,一些重要的应用如 A2DP, 基于 RFCOMM 的应用.BNEP等都要建立 ACL 链路,发送/接收ACL 包.跟大家一起来分析 ACL 包发送/接收 ...

  6. Jquery的$.ajax、$.get、$.post发送、接收JSON数据及回调函数用法

    平时研究代码时,经常会遇到AJAX的相关用法,做项目时才真正体会到Ajax的强大之处(与服务器数据交互如此之便捷,更新DOM节点而不用刷新整个页面),以及运用的频繁程度.今天整理了一下自己之前没搞清楚 ...

  7. 使用HttpRequester模拟发送及接收Json请求

    1.开发人员在火狐浏览器里经常使用的工具有Firebug,httprequester,restclient......火狐浏览器有一些强大的插件供开发人员使用!需要的可以在附加组件中扩展. 2.htt ...

  8. JSON入门指南--客户端处理JSON

    在传统的Web开发过程中,前端工程师或者后台工程师会在页面上写后台的相关代码,比如在ASP.NET MVC4里面写如下代码: @Html.TextBoxFor(m => m.UserName, ...

  9. jQuery form插件的使用--处理server返回的JSON, XML,HTML数据

    详细代码: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> & ...

随机推荐

  1. JMeter--一、安装JMeter

    Apache JMeter是Apache组织开发的基于Java的接口和性能测试工具. 作用: 1.能够对HTTP和FTP服务器进行压力和性能测试, 也可以对任何数据库进行同样的测试(通过JDBC). ...

  2. SQL 中 EXISTS 与 NOT EXISTS

    带有 EXISTS 操作符的子查询不返回任何数据,只产生逻辑真值 'true' 或逻辑假值 'false'.带有 EXISTS 操作符的子查询都是相关子查询. 相关子查询:子查询的条件依赖父查询. E ...

  3. 让虚拟机的软盘盘符不显示(适用于所有windows系统包括Windows Server)

  4. win8下IE10的鼠标mouse事件响应错误BUG

    具体症状就是有时候鼠标左键响应,有时候右键才能响应 问题的原因就是事件对象的detail没有复位 https://github.com/clientside/amplesdk/issues/187

  5. supportRequestWindowFeature与requestWindowFeature

    在Activity中去掉标题栏只需要在onCreate()中在setContentView前使用requestWindowFeature(). 在AppCompatActivity中去掉标题栏只需要在 ...

  6. Android 内存管理 &Memory Leak & OOM 分析

    转载博客:http://blog.csdn.net/vshuang/article/details/39647167 1.Android 进程管理&内存 Android主要应用在嵌入式设备当中 ...

  7. 校验码(海明校验,CRC冗余校验,奇偶校验)

    循环冗余校验码 CRC码利用生成多项式为k个数据位产生r个校验位进行编码,其编码长度为n=k+r所以又称 (n,k)码. CRC码广泛应用于数据通信领域和磁介质存储系统中. CRC理论非常复杂,一般书 ...

  8. WebAPi添加常用扩展方法及思维发散

    前言 在WebAPi中我们通常需要得到请求信息中的查询字符串或者请求头中数据再或者是Cookie中的数据,如果需要大量获取,此时我们应该想到封装一个扩展类来添加扩展方法,从而实现简便快捷的获取. We ...

  9. 【记录】VS2012新建MVC3/MVC4项目时,报:此模板尝试加载组件程序集“NuGet.VisualStudio.Interop...”

    最近电脑装了 VisualStudio "14" CTP,由于把其他版本的 VS 卸掉,由高到低版本安装,当时安装完 VisualStudio "14" CTP ...

  10. 触屏touch事件记录

    一.chrome中的Remote Debugging 一开始并没有用这个调试,不过后面需要多点触碰,可chrome模拟器中我没看到这个功能.突然看到了Remote Debugging,网站需要FQ才能 ...