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. Dash文档制作教程

    前言 什么是Dash 面向程序员的文档库(Mac) 代码片段管理工具 这是强烈推荐给每天在各种API文档中摸爬滚打的程序员们的神器. 为什么要自己制作文档 官方的源中没有相关文档 文档在离线下体验更好 ...

  2. lua解释执行脚本流程

    #include "lua.hpp" #include <iostream> using namespace std; #pragma comment(lib, &qu ...

  3. OPEN CASCADE Gauss Least Square

    OPEN CASCADE Gauss Least Square eryar@163.com Abstract. The least square can be used to solve a set ...

  4. SQL联合主键 查重

    2014年最后一天,今天在给数据库导入数据的时候,遇到一个问题,就是联合主键去重. 事情是这样的,现有一个表M,我想找个表中导入了许多数据,并需要将字段A(int)和B(int)联合设置为主键. 但是 ...

  5. IOS数据存储之FMDB数据库

    前言: 最近几天一直在折腾数据库存储,之前文章(http://www.cnblogs.com/whoislcj/p/5485959.html)介绍了Sqlite 数据库,SQLite是一种小型的轻量级 ...

  6. OracleDBA之表管理

    下面是Oracle表管理的部分,用到的测试表是oracle数据库中scott用户下的表做的测试,有的实验也用到了hr用户的数据,以下这些东西是我的麦库上存的当时学Oracle的学习笔记今天拿出来和大家 ...

  7. Android随笔之——静默安装、卸载

    随笔之所以叫随笔,就是太随意了,说起来,之前的闹钟系列随笔还没写完,争取在十月结束之前找时间把它给写了吧.今天要讲的Android APK的静默安装.卸载.网上关于静默卸载的教程有很多,更有说要调用隐 ...

  8. linux中断与异常

    看了<深入理解linux内核>的中断与异常,简单总结了下,如果有错误,望指正! 一 什么是中断和异常 异常又叫同步中断,是当指令执行时由cpu控制单元产生的,之所以称之为异常,是因为只有在 ...

  9. iPhone 6/plus iOS Safari fieldset border 边框消失

    问题:iPhone6 plus 手机浏览网页,fieldset border 边框消失. 示例代码: <div> <fieldset style="border: 1px ...

  10. T-Sql(七)用户权限操作(grant)

    一般数据库的权限操作我们很少用,除非一些大型的项目,需要给数据库配置不同的用户及权限,防患于未然,今天我们就来了解下t-sql中配置用户权限操作. 先看示例代码: --创建登录名 create log ...