springmvc处理json数据
springMVC提供了处理JSON格式请求/响应的HttpMessageConverter
MappingJckson2HttpMessageConverter利用Jackson开源类包处理JSON格式的请求或响应
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSON格式的数据接受</title>
<script type="text/javascript" src="js/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="js/json2.js"></script>
<script type="text/javascript">
$(document).ready(function () {
testRequestBody();
});
function testRequestBody() {
$.ajax("${pageContext.request.contextPath}/json/testRequestBody",// 发送请求的URL字符串。
{
dataType: "json", // 预期服务器返回的数据类型。
type: "post", // 请求方式 POST或GET
contentType: "application/json", // 发送信息至服务器时的内容编码类型
// 发送到服务器的数据。
data: JSON.stringify({id: 1, name: "张三"}),
async: true, // 默认设置下,所有请求均为异步请求。如果设置为false,则发送同步请求
// 请求成功后的回调函数。
success: function (data) {
console.log(data);
$("#id").html(data.id);
$("#name").html(data.name);
$("#author").html(data.author);
},
// 请求出错时调用的函数
error: function () {
alert("数据发送失败");
}
});
}
</script>
</head>
<body>
编号:<span id="id"></span><br>
书名:<span id="name"></span><br>
作者:<span id="author"></span><br>
</body>
</html>
BookController.java
package com.rookie.bigdata.controller;
import javax.servlet.http.HttpServletResponse;
import com.rookie.bigdata.domain.Book;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/json")
public class BookController {
private static final Log logger = LogFactory.getLog(BookController.class);
// @RequestBody根据json数据,转换成对应的Object
@RequestMapping(value="/testRequestBody")
public void setJson(@RequestBody Book book,
HttpServletResponse response) throws Exception{
// ObjectMapper类是Jackson库的主要类。它提供一些功能将Java对象转换成对应的JSON格式的数据
ObjectMapper mapper = new ObjectMapper();
// 将book对象转换成json输出
logger.info(mapper.writeValueAsString(book) );
book.setAuthor("许文强");
response.setContentType("text/html;charset=UTF-8");
// 将book对象转换成json写出到客户端
response.getWriter().println(mapper.writeValueAsString(book));
}
}
springmvc-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd">
<!-- spring可以自动去扫描base-pack下面的包或者子包下面的java文件,
如果扫描到有Spring的相关注解的类,则把这些类注册为Spring的bean -->
<context:component-scan base-package="org.fkit.controller"/>
<!-- 设置配置方案 -->
<mvc:annotation-driven/>
<!-- 使用默认的Servlet来响应静态文件 -->
<mvc:default-servlet-handler/>
<!-- 视图解析器 -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 前缀 -->
<property name="prefix">
<value>/WEB-INF/content/</value>
</property>
<!-- 后缀 -->
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
启动应用程序返回的截图如下
自定义HttpMessageConverter接受JSON格式的数据,采用fastJson来接受JSON数据
将上面的controller代码改为
@RequestMapping(value="/testRequestBody")
public void setJson(@RequestBody Book book,
HttpServletResponse response) throws Exception{
// 使用JSONObject将book对象转换成json输出
logger.info(JSONObject.toJSONString(book));
book.setAuthor("zhangsan");
response.setContentType("text/html;charset=UTF-8");
// 将book对象转换成json写出到客户端
response.getWriter().println(JSONObject.toJSONString(book));
}
配置文件改为下面这个即可跟前面访问的效果一样
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-4.2.xsd">
<!-- spring可以自动去扫描base-pack下面的包或者子包下面的java文件,
如果扫描到有Spring的相关注解的类,则把这些类注册为Spring的bean -->
<context:component-scan base-package="com.rookie.bigdata.controller"/>
<!-- 使用默认的Servlet来响应静态文件 -->
<mvc:default-servlet-handler/>
<!-- 设置配置方案 -->
<mvc:annotation-driven>
<!-- 设置不使用默认的消息转换器 -->
<mvc:message-converters register-defaults="false">
<!-- 配置Spring的转换器 -->
<bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
<bean class="org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter"/>
<bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/>
<bean class="org.springframework.http.converter.BufferedImageHttpMessageConverter"/>
<!-- 配置fastjson中实现HttpMessageConverter接口的转换器 -->
<bean id="fastJsonHttpMessageConverter"
class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<!-- 加入支持的媒体类型:返回contentType -->
<property name="supportedMediaTypes">
<list>
<!-- 这里顺序不能反,一定先写text/html,不然ie下会出现下载提示 -->
<value>text/html;charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<!-- 视图解析器 -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 前缀 -->
<property name="prefix">
<value>/WEB-INF/content/</value>
</property>
<!-- 后缀 -->
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
返回JSON数据格式
@RequestMapping(value="/testresponse")
// @ResponseBody会将集合数据转换json格式返回客户端
@ResponseBody
public Object getJson() {
List<Book> list = new ArrayList<Book>();
list.add(new Book(1,"java","lisi"));
list.add(new Book(2,"徐文清","wangwu"));
return list;
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>测试返回JSON格式的数据</title>
<script type="text/javascript" src="js/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="js/json2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
testResponseBody();
});
function testResponseBody(){
$.post("${pageContext.request.contextPath}/json/testresponse",null,
function(data){
$.each(data,function(){
var tr = $("<tr align='center'/>");
$("<td/>").html(this.id).appendTo(tr);
$("<td/>").html(this.name).appendTo(tr);
$("<td/>").html(this.author).appendTo(tr);
$("#booktable").append(tr);
})
},"json");
}
</script>
</head>
<body>
<table id="booktable" border="1" style="border-collapse: collapse;">
<tr align="center">
<th>编号</th>
<th>书名</th>
<th>作者</th>
</tr>
</table>
</body>
</html>
springmvc处理json数据的更多相关文章
- 【Spring学习笔记-MVC-3.1】SpringMVC返回Json数据-方式1-扩展
<Spring学习笔记-MVC>系列文章,讲解返回json数据的文章共有3篇,分别为: [Spring学习笔记-MVC-3]SpringMVC返回Json数据-方式1:http://www ...
- SpringMVC(三)-- 视图和视图解析器、数据格式化标签、数据类型转换、SpringMVC处理JSON数据、文件上传
1.视图和视图解析器 请求处理方法执行完成后,最终返回一个 ModelAndView 对象 对于那些返回 String,View 或 ModeMap 等类型的处理方法,SpringMVC 也会在内部将 ...
- 【Spring学习笔记-MVC-4】SpringMVC返回Json数据-方式2
<Spring学习笔记-MVC>系列文章,讲解返回json数据的文章共有3篇,分别为: [Spring学习笔记-MVC-3]SpringMVC返回Json数据-方式1:http://www ...
- 【Spring学习笔记-MVC-3】SpringMVC返回Json数据-方式1
<Spring学习笔记-MVC>系列文章,讲解返回json数据的文章共有3篇,分别为: [Spring学习笔记-MVC-3]SpringMVC返回Json数据-方式1:http://www ...
- SpringMVC返回JSON数据时日期格式化问题
https://dannywei.iteye.com/blog/2022929 SpringMVC返回JSON数据时日期格式化问题 博客分类: Spring 在运用SpringMVC框架开发时,可 ...
- SpringMVC传递JSON数据
文章目录 一.前后端传递和接收JSON数据 1:是要Ajax默认格式来传递数据(*) 2:使用application/json格式来传递数据 二.spring-web.xml中需要如下配置 一.前后端 ...
- SpringMVC之json数据传递
json是一种常见的传递格式,是一种键值对应的格式.并且数据大小会比较小,方便传递.所以在开发中经常会用到json. 首先看一下json的格式: {key1:value1,key2:value2} 每 ...
- SpringMVC的JSON数据交互(七)-@Response,@RestController,@RequestBody用法
1.@RequestBody (自动将请求的数据封装为对象) 作用: @RequestBody注解用于读取http请求的内容(字符串),通过springmvc提供的HttpMessageConve ...
- springmvc的json数据交互
准备 @RequestBody 作用: @RequestBody注解用于读取http请求的内容(字符串),通过springmvc提供的HttpMessageConverter接口将读到的内容(json ...
- springMVC返回json数据乱码问题及@RequestMapping 详解
原文地址:https://blog.csdn.net/u010127245/article/details/51774074 一.@RequestMapping RequestMapping是一个用来 ...
随机推荐
- 仿照手机写一个WIFI的操作程序
本篇博客仿照手机的功能,写一个WIFI的操作程序. 手机的WIFI功能有哪些呢?当我们进入wlan的设置界面的时候,将自动识别出若干个wifi的热点,并且会自动更新,当点击某个wifi热点的时候,然后 ...
- Google Chrome 解决 “您的连接不是私密连接” 和被毒霸劫持
一.解决 “您的连接不是私密连接” 前一段时间,Chrome 突然显示出了“您的连接不是私密连接”,这下可难受了,大部分的网站打开都有问题. 找了各种方法,各种设置都是不行. 一.暴力.费力的方法直接 ...
- vue响应数据的原理
vue最大的特点就是数据驱动视图. vue的数据改变,页面一定发生改变?不一定. 当操作引用类型的数据,动态添加属性时,页面不会发生改变. vue响应式数据原理(也叫数据绑定原理.双向数据绑定原理): ...
- 牛逼哄哄的 Lambda 表达式,简洁优雅就是生产力!
阅读本文大概需要 4 分钟. 作者:Sevenvidia https://www.zhihu.com/question/20125256/answer/324121308 什么是Lambda? 我们知 ...
- cad问题小百科 持续更新
一些浩辰的问题移步去: 浩辰问题 (浩辰可能和桌子具有相同的问题,所以这篇你可能还是要看 cad2007遇到了这种情况 安装问题安装CAD出现C++2005问题的解决方法,出现此问题,原 ...
- pandas 获取不符合条件的dataframe
pandas 获取不符合条件的dataframe 或将其过滤掉: df[df["col"].str.contains('this'|'that')==False] >> ...
- 分布式系统中我们会对一些数据量大的业务进行分拆,分布式系统中唯一主键ID的生成问题
分布式全局唯一ID生成策略 https://www.cnblogs.com/vandusty/p/11462585.html 一.背景 分布式系统中我们会对一些数据量大的业务进行分拆,如:用户表,订 ...
- 爬虫框架 ---- scrapy 框架的介绍与安装
----- 爬虫 基于B/S 模式的数据采集技术,按照一定的规则,自动的抓取万维网信息程序 以一个或多个页面为爬取起点,从页面中提取链接实现深度爬取 使用爬虫的列子 第三方抢票软件(360/猎豹/ ...
- git 命令行回退到某个指定的版本
1.在开发过程中遇到合并别人的代码或者合并主分支的代码导致自己的分支代码冲突或有别的问题,这时我们需要回退某个git提交历史的代码 用一下命令 git reset --hard 139dcfaa558 ...
- 更新Linux内核
说明:为了安装Docker,当前虚拟机不满足要求,版本如下: [root@localhost116 ~]# uname -r -.el6.x86_64 [root@localhost116 ~]# c ...