版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/kshon/article/details/82532051
一、使用jackson处理json
1、下载jackson的jar包https://download.csdn.net/download/kshon/10654076
2、下载jquery,这个可以直接去官网下载
3、下载json2的js文件https://download.csdn.net/download/kshon/10654093
4、将jackson的jar导入到WEB-INF/lib目录下,在WebContent目录下新建一个style/js目录,并加入jquery和json2的js文件
5、页面index.jsp,位于WebContent目录下
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>json数据</title>
<script type="text/javascript" src="style/js/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="style/js/json2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
testRequestBody();
})
function testRequestBody(){
$.ajax("${pageContext.request.contextPath}/json/testRequestBody",{
dataType:"json", //服务器返回的数据类型
type:"post", //请求方式
contentType:"application/json", //内容编码格式
data:JSON.stringify({id:1,name:"spring mvc应用实战"}), //发送的数据
async:true, //异步请求
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>
6、编写book对象(src/pojo/Book.java)
package pojo;
public class Book {
private int id;
private String name;
private String author;
public Book(){}
public Book(int id,String name,String author){
this.id = id;
this.name = name;
this.author = author;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}
7、编写BookController(src/controller/BookController.java)
package controller;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
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;
import kshon.pojo.Book;
@Controller
@RequestMapping("/json")
public class BookController {
@RequestMapping("/testRequestBody")
//@RequestBody会根据json数据,转换成对应的Object
public void setJson(@RequestBody Book book, HttpServletResponse response){
//ObjectMapper是jackson库的主要 类,它提供一些功能将java对象转换成json数据
ObjectMapper mapper = new ObjectMapper();
try {
//book对象转换成json输出
System.out.println(mapper.writeValueAsString(book));
book.setAuthor("廖坤雄");
response.setContentType("text/html;charset=UTF-8");
//将book对象转换成json写出到页面
response.getWriter().println(mapper.writeValueAsString(book));
} catch (JsonGenerationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
8、spring配置文件WEB-INF/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-package下面的包或子包下面的java文件 -->
<context:component-scan base-package="kshon.controller,kshon.pojo" />
<!-- 设置配置方案 -->
<mvc:annotation-driven />
<!-- 使用默认的servlet响应静态文件 -->
<mvc:default-servlet-handler/>
<!-- 配置annotation类型的处理映射器 -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
<!-- 配置annotation类型的处理器适配器 -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>
<!-- 视图解析器 -->
<bean 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>
接下来启动tomcat,输入http://localhost:8080/SpringMVC/index.jsp即可访问
二、使用fastjson处理JSON数据
1、下载fastjson所需jar包https://download.csdn.net/download/kshon/10654082,加入到WEB-INF/lib
2、其他内容不变,修改src/controller/BookController.java类
package kshon.controller;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
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;
import com.alibaba.fastjson.JSONObject;
import kshon.pojo.Book;
@Controller
@RequestMapping("/json")
public class BookController {
@RequestMapping("/testRequestBody")
//@RequestBody会根据json数据,转换成对应的Object
public void setJson(@RequestBody Book book, HttpServletResponse response) throws IOException{
System.out.println(JSONObject.toJSONString(book));
book.setAuthor("廖坤雄");
response.setContentType("text/html;charset=UTF-8");
//将book对象转换成json写出到页面
response.getWriter().println(JSONObject.toJSONString(book));
}
}
三、前台页面接收json数据
1、在src/controller/BookController.java中添加一个getJson方法,用于返回Json数据到页面
@RequestMapping("/getJson")
@ResponseBody //ResponseBody会将集合数据转换为json格式并返回到页面
public Object getJson(){
List<Book> list = new ArrayList<Book>();
list.add(new Book(1,"English","牛津大神"));
list.add(new Book(2,"明朝那些事儿","二月红"));
return list;
}
2、修改WebContent/index.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>json数据</title>
<script type="text/javascript" src="style/js/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="style/js/json2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
getJson();
})
function testRequestBody(){
$.ajax("${pageContext.request.contextPath}/json/testRequestBody",{
dataType:"json", //服务器返回的数据类型
type:"post", //请求方式
contentType:"application/json", //内容编码格式
data:JSON.stringify({id:1,name:"spring mvc应用实战"}), //发送的数据
async:true, //异步请求
success:function(data){ //回调函数
console.log(data);
$("#id").html(data.id);
$("#name").html(data.name);
$("#author").html(data.author);
},
error:function(){
alert("数据发送失败");
}
})
}
function getJson(){
$.post("${pageContext.request.contextPath}/json/getJson",null,function(data){
console.log(data);
$.each(data,function(){
$("#book").append("<li>"+this.id+"</li>");
$("#book").append("<li>"+this.name+"</li>");
$("#book").append("<li>"+this.author+"</li>");
},"json");
});
}
</script>
</head>
<body>
<ul id="book"></ul>
</body>
</html>