spring mvc返回json字符串的方式
方案一:使用@ResponseBody 注解返回响应体 直接将返回值序列化json
优点:不需要自己再处理
步骤一:在spring-servlet.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:p="http://www.springframework.org/schema/p"
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.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.xsd ">
<!--使用Annotation方式 完成映射 -->
<!--让spring扫描包下所有的类,让标注spring注解的类生效 -->
<context:component-scan base-package="cn.yxj.controller"/>
<mvc:annotation-driven/>
<!--视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
步骤二:在处理器方法中打上@ResponseBody 标签
@RequestMapping(value="/hello5.do")
@ResponseBody
public String hello(HttpServletResponse response) throws IOException{
UserInfo u1=new UserInfo();
u1.setAge(15);
u1.setUname("你好");
UserInfo u2=new UserInfo();
u2.setAge(152);
u2.setUname("你好2");
Map<String,UserInfo> map=new HashMap<String, UserInfo>();
map.put("001", u1);
map.put("002", u2);
String jsonString = JSON.toJSONString(map);
return jsonString;
}
步骤三:使用ajax进行获取数据
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<script type="text/javascript" src="js/jquery-1.8.3.js"></script>
<script type="text/javascript">
$(function(){
$("#btn").click(function(){
$.ajax({
url:"<%=path%>/Five.do",
success:function(data){
//解析对象
//alert(data.uname+"\n"+data.age);
//解析map
//alert(data.info.age+"\n"+data.info.uname);
//解析list
$.each(data,function(i,dom){
alert(dom.uname+"\n"+dom.age);
});
}
});
});
});
</script>
</head>
<body>
<input type="button" value="ajax" id="btn"/>
</body>
</html>
方案二:处理器方法的返回值---Object
由于返回Object数据,一般都是将数据转化为JSON对象后传递给浏览器页面的,而这个由Object转换为Json,是由Jackson工具完成的,所以要导入jar包,将Object数据转化为json数据,需要Http消息
转换器 HttpMessageConverter完成。而转换器的开启,需要由<mvc:annotation-driven/> 来完成,当spring容器进行初始化过程中,在<mvc:annotation-driven/> 处创建注解驱动时,默认创
建了七个HttpMessageConverter对象,也就是说,我们注册<mvc:annotation-driven/>,就是为了让容器帮我们创建HttpMessageConverter对象
详细代码看
方案二、使用返回字符串的处理器方法,去掉@ResponseBody注解
步骤一、同上
步骤二
@RequestMapping(value="/hello5.do")
public String hello(HttpServletResponse response) throws IOException{
UserInfo u1=new UserInfo();
u1.setAge(15);
u1.setUname("你好");
UserInfo u2=new UserInfo();
u2.setAge(152);
u2.setUname("你好2");
Map<String,UserInfo> map=new HashMap<String, UserInfo>();
map.put("001", u1);
map.put("002", u2);
String jsonString = JSON.toJSONString(map);
return jsonString;
}
步骤三、在前台取值的时候需要我么做一遍处理
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<script type="text/javascript" src="js/jquery-1.8.3.js"></script>
<script type="text/javascript">
$(function(){
$("#btn").click(function(){
$.ajax({
url:"<%=path%>/hello5.do",
success:function(data){ //data指的是从server打印到浏览器的数据
//jsonString jsonObject
//{"001":{"age":122,"name":"顺利就业"}}
var result= eval("("+data+")");
$.each(result,function(i,dom){
alert(dom.age+"\n"+dom.uname);
});
// alert(result["001"]["age"]);
}
});
});
});
</script>
</head>
<body>
<input type="button" value="ajax" id="btn"/>
</body>
</html>
方案三:使用无返回值的处理器方法
步骤一:同上
步骤二:使用响应流回送数据
@RequestMapping(value="/hello5.do")
public void hello(HttpServletResponse response) throws IOException{
UserInfo u1=new UserInfo();
u1.setAge(15);
u1.setUname("你好");
UserInfo u2=new UserInfo();
u2.setAge(152);
u2.setUname("你好2");
Map<String,UserInfo> map=new HashMap<String, UserInfo>();
map.put("001", u1);
map.put("002", u2);
String jsonString = JSON.toJSONString(map);
response.setCharacterEncoding("utf-8");
response.getWriter().write(jsonString);
response.getWriter().close();
}
步骤三:在前台取值也需要做处理
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<script type="text/javascript" src="js/jquery-1.8.3.js"></script>
<script type="text/javascript">
$(function(){
$("#btn").click(function(){
$.ajax({
url:"<%=path%>/hello5.do",
success:function(data){ //data指的是从server打印到浏览器的数据
//jsonString jsonObject
//{"001":{"age":122,"name":"顺利就业"}}
var result= eval("("+data+")");
$.each(result,function(i,dom){
alert(dom.age+"\n"+dom.uname);
});
// alert(result["001"]["age"]);
}
});
});
});
</script>
</head>
<body>
<input type="button" value="ajax" id="btn"/>
</body>
</html>
前台代码:
function channel(){
//先获取选中的值
var channelId = $("#channelId option:selected").val();
//来判断发送的链接
if(channelId ==2){
**需要注意地方 start**
var schoolBannerInfo = {
"img": channelId,
"title": channelId,
"info": channelId,
"channelId": channelId
};
**需要注意地方 end**
$.ajax({
url:"ceshijson",
type:"post",
dataType:'json',
**需要注意地方 start**
contentType:'application/json;charset=utf-8',
data:JSON.stringify(schoolBannerInfo),
**需要注意地方 end**
success:function(data){
alert(data);
},
error:function(XMLHttpRequest, textStatus, errorThrown){
alert("Error")
alert(XMLHttpRequest.status);
alert(XMLHttpRequest.readyState);
alert(textStatus);
}
});
}
}
加粗的部分是要注意的地方。
其中contentType:’application/json;charset=utf-8’不能省掉,否则会报415错误。
毕竟我发送的是json字符串,得告诉服务器,来的数据是json数据。
JSON.stringify()是将JavaScript对象转换为json字符串
JSON.parse(jsonstr)是将json字符串转换为JavaScript对象
补充知识:json其实就是JavaScript的子集。
参考地址:http://www.jb51.net/article/35090.htm
后台代码:
pojo类:
public class SchoolBannerInfo {
private Integer id;
private Date createTime;
private String img;
private String title;
private String info;
private Integer seq;
private Integer schoolId;
private String type;
private boolean enable;
private String link;
private String channelId;
}
get与set方法自己生成,这个就不贴出来了。
controller中方法:
@RequestMapping(value="/ceshijson",produces="application/json;charset=UTF-8")
@ResponseBody
public SchoolBannerInfo ceshijson(@RequestBody SchoolBannerInfo schoolBannerInfo) throws IOException{
// Map<String,Object> map = new HashMap<String,Object>();
// map.put("channelId", channelId);
// ObjectMapper mapper = new ObjectMapper();
// channelId = mapper.writeValueAsString(map);
return schoolBannerInfo;
}
注意:
1、@RequestBody不能省,因为前台发过来的数据是json数据,得用这个注解去解析该怎么接收这些数据给pojo类的对象。
2、因为我也要返回json数据。所以需要这个注解@ResponseBody,把Java对象转换成json字符串
3、当使用@RequestBody时,要求前台传过来的数据是json字符串。如果是json对象是会出错的。所以如果你前台data部分这么写:data:{“channelId”:2},这样是不行的。因为{“channelId”:2}是json对象,你需要再在外层加个引号’{“channelId”:2}’这样才行。
4、要是方法返回值为简单类型比如:String时,该如何处理呢!下篇讲解。