一、简单应用
1、controller层接收json数据并返回json数据
package top.einino.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import top.einino.pojo.User;
@Controller
public class UserController {
//@RequestBody将json数据转换成user
//@ResponseBody将user对象转换成json数据
@RequestMapping("/requestJson.action")
public @ResponseBody User requestJson(@RequestBody User user){
return user;
}
}
2、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>
<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-1.4.4.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
function requestJson(){
$.ajax({
//请求方式
type:'post',
//请求地址
url:'${pageContext.request.contextPath}/requestJson.action',
//请求数据类型
contentType:'application/json;charset=utf-8',
//请求数据
data:'{"id":1,"username":"李四"}',
//回调函数
success:function(data){
alert(data.id);
alert(data.username);
}
});
}
</script>
</head>
<body>
<input type="button" οnclick="requestJson()" value="进行json交互"/>
</body>
</html>
3、springmvc中主要配置
<!-- 注解驱动 ,同时包含json数据的转换-->
<mvc:annotation-driven></mvc:annotation-driven>
二、小结
本博文介绍了springmvc的json数据交互,主要利用两个注解@RequestBody和@ResponseBody进行数据的转换。
如果有疑问或者对本博文有何看法或建议或有问题的,欢迎评论,恳请指正!