spring MVC通过json与前台交互
这里用的是spring4.1.4,jquery2.1.3,其它环境为:myeclipse2014,tomcat7,jdk7




<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd"> <!-- 启用注解 -->
<mvc:annotation-driven /> <!-- 配置默认首页 -->
<mvc:view-controller path="/" view-name="index"/> <!-- 处理对静态资源的访问请求 -->
<mvc:resources location="/WEB-INF/static/js/" mapping="/js/**"/> <!-- 扫描controller注解 -->
<context:component-scan base-package="com.controller" /> <!-- 解析视图 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsps/" />
<property name="suffix" value=".jsp" />
</bean> </beans>
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>JsonDemo</display-name> <servlet>
<servlet-name>springMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:springMVC-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet> <servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
public class User
{
private Integer id;
private String username;
private String password;
private String address; //getter and setter
}
<table id="tab">
<tr>
<th>Id</th>
<th>username</th>
<th>password</th>
<th>address</th>
</tr>
</table>
$(document).ready(
function() {
//当页面载入完成后,通过$.post方法从后台获取到list数据,并将它们插入到表格中
//data是后台返回的json字符串,statusText为error或者success
$.post("user/list", function(data, statusText) { for (var i = 0; i < data.length; i++) {
var temp = "<tr>";
temp += "<td>" + data[i].id + "</td><td>"
+ data[i].username + "</td><td>"
+ data[i].password + "</td><td>"
+ data[i].address + "</td>";
$('#tab').append(temp + "</tr>");
} }, "json");
});
@Controller
@RequestMapping("/user")
public class JsonController
{
@RequestMapping("/list")
public String getAllUser(Model model)
{
return "list";
} @RequestMapping(value = "/list", method = RequestMethod.POST)
@ResponseBody
public String userListJson(Model model)
{
Gson gson = new Gson();
String str = gson.toJson(createUserList(5));
return str;
}
//创建5个用户
private List<User> createUserList(Integer count)
{
List<User> result = new ArrayList<User>();
for (int i = 1; i <= count; i++)
{
User user = new User();
user.setId(i);
user.setUsername("user" + i);
user.setPassword("admin" + i);
user.setAddress(i + "地区");
result.add(user);
}
return result;
}
}
<form id="test">
<table>
<tr>
<th>Id</th>
<td><input type="text" name="id"></td>
</tr>
<tr>
<th>username</th>
<td><input type="text" name="username"></td>
</tr>
<tr>
<th>password</th>
<td><input type="text" name="password"></td>
</tr>
<tr>
<th>address</th>
<td><select name="address">
<option value="beijing">北京</option>
<option value="shanghai">上海</option>
<option value="guangzhou">广州</option>
</select></td>
</tr>
</table>
</form>
<button id="btn1">添加</button>
<table id="tab">
<tr>
<th>Id</th>
<th>username</th>
<th>password</th>
<th>address</th>
</tr>
</table>
//当用户点击id为btn1的按钮时,通过serializeArray()方法获取到表单中的数据,然后通过$.each将
//这些数据封装成json对象,最后使用JSON.stringify()方法将json对象转换成json字符串并发送给后台
$('#btn1').click(
function() {
var str = $('#test').serializeArray();
var sendData = {};
$.each(str, function() {
if (this.value == null) {
sendData[this.name] = '';
} else {
sendData[this.name] = this.value;
} });
$.ajaxSetup({
contentType : 'application/json'
});
//同上
$.post("user/add", JSON.stringify(sendData),
function(data, statusText) {
var temp = "<tr>";
temp += "<td>" + data.id + "</td><td>"
+ data.username + "</td><td>"
+ data.password + "</td><td>"
+ data.address + "</td>";
$('#tab').append(temp + "</tr>"); }, "json");
});
@RequestMapping(value = "/add", method = RequestMethod.POST)
@ResponseBody
public String getJsonMsg(@RequestBody User user)
{
System.out.println(user.getId() + "|" + user.getUsername() + "|"
+ user.getPassword() + "|" + user.getAddress());
return new Gson().toJson(user);
}


spring MVC通过json与前台交互的更多相关文章
- spring mvc返回json字符串的方式
spring mvc返回json字符串的方式 方案一:使用@ResponseBody 注解返回响应体 直接将返回值序列化json 优点:不需要自己再处理 步骤一:在spring- ...
- spring mvc返回json字符串数据,只需要返回一个java bean对象就行,只要这个java bean 对象实现了序列化serializeable
1.spring mvc返回json数据,只需要返回一个java bean对象就行,只要这个java bean 对象实现了序列化serializeable 2. @RequestMapping(val ...
- Spring Mvc 输出Json(iwantmoon.com出品)
原文:http://iwantmoon.com/Post/f94e49caf9b6455db7158474bab4c4dd 因为工作需要,现在要去做开放平台,考虑了多种方案之后,基本确定 下来,Htt ...
- Spring MVC 的json问题(406 Not Acceptable)
原因 : 就是程序转换JSON失败. 在pom.xml 加上 <dependency> <groupId>com.fasterxml.jackson.core</grou ...
- ajax使用向Spring MVC发送JSON数据出现 org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported错误
ajax使用向Spring MVC发送JSON数据时,后端Controller在接受JSON数据时报org.springframework.web.HttpMediaTypeNotSupportedE ...
- Spring MVC之JSON数据交互和RESTful的支持
1.JSON概述 1.1 什么是JSON JSON(JavaScript Object Notation,JS对象标记)是一种轻量级的数据交换格式.它是基于JavaScript的一个子集,使用了C.C ...
- Spring MVC与html页面的交互(以传递json数据为例)
一.导入相jar包 主要包括spring相关jar包和fastjson jar包,具体步骤略. 二.配置相关文件 1.配置web.xml文件 <?xml version="1.0&qu ...
- Spring MVC 接收Json格式参数
今天做了一个关于表格排序的功能,可以通过右边的箭头做排序操作,每次操作需要通过Ajax将每条记录的Id数组作为参数去发送请求, 后台Spring MVC接到参数后作更改序号操作. 前端页面发送请求的代 ...
- Spring MVC返回json数据给Android端
原先做Android项目时,服务端接口一直是别人写的,自己拿来调用一下,但下个项目,接口也要自己搞定了,我想用Spring MVC框架来提供接口,这两天便抽空浅学了一下该框架以及该框架如何返回json ...
随机推荐
- java 编码 UTF-8、ISO-8859-1、GBK 【转】
Java支持UTF-8.ISO-8859-1.GBK等各种字体编码,可笔者发现Java中字体编码的问题仍难倒了不少程序员,网上虽然也有不少关于在Java中如何正确显示中文的文章,但都不够全面,笔者特意 ...
- 打开本地STL文件并创建webgl使用的geometry
需求 打开本地STL文件 一个独立基于webgl的viewer,会被别的网站重用 将打开文件的数据传输给viewer,并且在文件加载的时候显示进度条 解决方案 #1可以使用传统的html5 api来打 ...
- ASP.NET-Web-API-Poster.pdf flow chart
下载地址
- 【FSFA 读书笔记】Ch 2 Computer Foundatinons(2)
Hard Disk Technology 1. 机械硬盘内部构造 几个重要概念:Sector(扇区),Head(读写头),Track(磁道),Cylinder(柱面). 如果一个文件比较大,磁盘的写入 ...
- 【POJ 2823 Sliding Window】 单调队列
题目大意:给n个数,一个长度为k(k<n)的闭区间从0滑动到n,求滑动中区间的最大值序列和最小值序列. 最大值和最小值是类似的,在此以最大值为例分析. 数据结构要求:能保存最多k个元素,快速取得 ...
- 单链表反转(递归和非递归) (Java)
链表定义 class ListNode { int val; ListNode next; ListNode(int x) { val = x; } } 非递归实现很简单,只需要遍历一遍链表,在遍历过 ...
- #include <bitset>
1 none();测试是否有越位 2 reset();全部清零 3 set(7, 0);把第7个字符改成0,操作二进制位 4 to_string();转换为字符串 5 to_ulong();转换为无符 ...
- OC基础14:使用文件
"OC基础"这个分类的文章是我在自学Stephen G.Kochan的<Objective-C程序设计第6版>过程中的笔记. 1.对于NSFileManager类,文件 ...
- JAVA学习第二十九课(经常使用对象API)- String类
多线程告一段落,開始经常使用对象API的涉及,背也要背下来!.! 日后开发,遇见最多的对象是文字,也就是字符串 String类 字符串是一个特殊对象 字符串一旦初始化就不能够被改变 一.特点 publ ...
- Invalid file permission Please regenerate them with cacaoadm create-keys --force
1.服务器重启之后,启动cacao报错,提示无效的文件权限. [root@ldapserver bin]# ./cacaoadm start Invalid file permission: [/ho ...