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 ...
随机推荐
- ASCII码排序,hdu-2000
Problem Description 输入三个字符后,按各字符的ASCII码从小到大的顺序输出这三个字符. Input 输入数据有多组,每组占一行,有三个字符组成,之间无空格. Output ...
- GDAL库——读取图像并提取基本信息
GDAL库是一个跨平台的栅格地理数据格式库,包括读取.写入.转换.处理各种栅格数据格式(有些特定的格式对一些操作如写入等不支持).它使用了一个单一的抽象数据模型就支持了大多数的栅格数据.这里有GDAL ...
- Can't create a new thread (errno 11); if you are not out of available memory, you can consult the manual for a possible OS-dependent bug
解决方案: http://www.javatang.com/archives/2013/06/19/2701909.html
- (十一)boost库之多线程间通信
(十一)boost库之多线程间通信 1.互斥锁 在编程中,引入了对象互斥锁的概念,来保证共享数据操作的完整性.每个对象都对应于一个可称为" 互斥锁" 的标记,这个标记用来保证在任一 ...
- 【LeetCode练习题】Unique Paths
Unique Paths A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagra ...
- Java面试题之九
四十六.Math.round(11.5)等於多少? Math.round(-11.5)等於多少? 对于这个题,只要弄清楚Math提供的三个与取整相关的方法就OK了. 1.ceil,英文含义是天花板,该 ...
- Lotto(dfs)
Lotto Time Limit : 2000/1000ms (Java/Other) Memory Limit : 131072/65536K (Java/Other) Total Submis ...
- 通过 Autostereograms 案例学习 OpenGL 和 OpenCL 的互操作性
引言 在过去的十年里, GPU (图形处理单元)已经从特殊硬件(特供)转变成能够在数值计算领域开辟新篇章的高性能计算机设备. 很多算法能够使用拥有巨大的处理能力的GPU来快速运行和处理大数据量.即使在 ...
- GCC单独编译host/examples/ tx_waveforms.cpp
1.编译 须要链接uhd库和boost_program_options库以及boost_thread库: g++ tx_waveforms.cpp -o a -luhd -lboost_program ...
- JavaScript判断图片是否加载完成
一.load事件 <!DOCTYPE HTML><html> <head> <meta charset="utf-8"> ...