(Spring4 json入门)Spring4+SpringMVC+页面数据发送与接收(json格式)
jar包(Maven仓库):
在测试过程中我查看了网上的一些教程,但是那些教程都是在Spring3环境下的,Spring3和Spring4解析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格式)的更多相关文章
- ASP.NET POST XML JSON数据,发送与接收
接收端通过Request.InputStream读取:byte[] byts = new byte[Request.InputStream.Length];Request.InputStream.Re ...
- [java,2018-01-16] HttpClient发送、接收 json 请求
最近需要用到许多在后台发送http请求的功能,可能需要发送json和xml类型的数据. 就抽取出来写了一个帮助类: 首先判断发送的数据类型是json还是xml: import org.dom4j.Do ...
- 使用httperrequest,模拟发送及接收Json请求
使用httpreques\Json-Handle\tcpdump\wireshark工具进行,抓取手机访问网络的包,分析request及response请求,通过httprequester来实现模拟发 ...
- 使用firefox插件httperrequest,模拟发送及接收Json请求 【转】
转自[http://blog.csdn.net/feixue1232/article/details/8535212] 目标:使用httpreques\Json-Handle\tcpdump\wire ...
- L2CAP数据发送和接收
ACL 链路在 Bluetooth 中非常重要,一些重要的应用如 A2DP, 基于 RFCOMM 的应用.BNEP等都要建立 ACL 链路,发送/接收ACL 包.跟大家一起来分析 ACL 包发送/接收 ...
- Jquery的$.ajax、$.get、$.post发送、接收JSON数据及回调函数用法
平时研究代码时,经常会遇到AJAX的相关用法,做项目时才真正体会到Ajax的强大之处(与服务器数据交互如此之便捷,更新DOM节点而不用刷新整个页面),以及运用的频繁程度.今天整理了一下自己之前没搞清楚 ...
- 使用HttpRequester模拟发送及接收Json请求
1.开发人员在火狐浏览器里经常使用的工具有Firebug,httprequester,restclient......火狐浏览器有一些强大的插件供开发人员使用!需要的可以在附加组件中扩展. 2.htt ...
- JSON入门指南--客户端处理JSON
在传统的Web开发过程中,前端工程师或者后台工程师会在页面上写后台的相关代码,比如在ASP.NET MVC4里面写如下代码: @Html.TextBoxFor(m => m.UserName, ...
- jQuery form插件的使用--处理server返回的JSON, XML,HTML数据
详细代码: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> & ...
随机推荐
- Azure PowerShell (3) 上传证书
<Windows Azure Platform 系列文章目录> 本文介绍的是国外的Azure Global Update 2015-09-01 发现一个新的命令,在Azure PowerS ...
- 《Entity Framework 6 Recipes》中文翻译系列 (6) -----第二章 实体数据建模基础之使用Code First建模自引用关系
2-5 使用Code First建模自引用关系 问题 你的数据库中一张自引用的表,你想使用Code First 将其建模成一个包含自关联的实体. 解决方案 我们假设你有如图2-14所示的数据库关系图的 ...
- windows命令——taskkill
C:\Users\Administrator>taskkill /? TASKKILL [/S system [/U username [/P [password]]]] { [/FI filt ...
- Objective-C 桥接模式 -- 简单实用和说明
桥接模式---把两个相关联的类抽象出来, 以达到解耦的目的 比如XBox遥控器跟XBox主机, 我们抽象出主机和遥控器两个抽象类, 让这两个抽象类耦合 然后生成这两个抽象类的实例XBox & ...
- 2013 duilib入门简明教程 -- 自绘标题栏(5)
如果大家有做过标题栏的自绘,肯定会感慨各种不容易,并且现有的一些资料虽然完美的实现了功能,但是代码比较乱,需要自行整理.如果用duilib,就是小case啦. duilib其实并没有区 ...
- Eos开发——ajax请求
function saveData(){ form.validate(); if(form.isValid()==false) return; var persons = grid.getChange ...
- android studio和eclipse中如何获取sha1值
首先如果是eclipse的话, 直接打开eclipse开发工具 那么接下来问题来了,现在很多开发者都已经从es转型到as开发工具了, 在android studio上没有直接提供这个GUI界面让我们去 ...
- OpenCASCADE View Manipulator
OpenCASCADE View Manipulator eryar@163.com Abstract. When you finish modeling objects in the scene, ...
- php的mysql\mysqli\PDO(二)mysqli
原文链接:http://www.orlion.ga/1147/ mysqli有面向对象风格和面向过程风格,个人感觉还是用面向对象风格比较好(毕竟是面向对象) 1.mysqli::_construct( ...
- Vim 快速上手
1.vi的基本概念 基本上vi可以分为三种状态,分别是 命令模式(command mode) 插入模式(Insert mode) 底行模式(last line mode) 1) 命令行模式comman ...