Object可以是Integer、String、自定义对象、Map、List等 ,返回对象
需要使用@ResponseBody注解,将转换为后的JSON数据存放到响应体中,对象有属性,属性就是数据,所以返回Object表示数据,和视图无关。可以使用对象表示数据,响应ajax请求
现在Ajax,主要使用json的数据格式,实现步骤:
1、加处理json的工具库的依赖,springmvc默认使用的是Jackson
2、在springmvc配置文件之间加入<mvc:annotation-driver>注解驱动
原理:就是把Java对象转为json
json = om.writeValueAsString(student);
3、在处理器方法的上面加上@ResponseBody注解(就是把json数据输出)
原理:输出数据,响应ajax的请求
PrintWriter wr = response.getWriter();
wr.println(json);
wr.flush();
wr.close();
代码演示
spring.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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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 https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="cn.com.Ycy.Contrller"/>
<mvc:annotation-driven/>
</beans>
user类:
public class user {
private String username;
private int age;
private String birthday;
private String sex;
private String tellphone;
//set/get方法
}
页面代码:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<meta http-equiv="Content-Type" content="textml; charset=UTF-8">
<title>Title</title>
<script type="text/javascript" src="js/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btn").click(function () {
$.ajax({
url:"returnObject.do",
data:{
username:$("#name").val(),
//后台获取的数据都是字符串的格式。需要和user对象的属性类型对应
age:Number($("#age").val()),
birthday:$("#birthday").val(),
sex:$(":radio:checked").val(),
tellphone:$("#tellphone").val()
},
type:"post",
dataType:"json",
success:function (data) {
//jQuery会把字符串转为json对象,赋值给data形参
alert(data.username+" "+data.age+" "+data.sex);
},
error:function () {
alert("error!!");
}
})
})
})
</script>
<style>
input {
outline: none;
border: none;
}
</style>
</head>
<body>
<form action="return-View.do" method="post">
<table width="300px" border="1" cellpadding="0" cellspacing="0">
<tr>
<td>姓名</td>
<td><input type="text"name="username" id="name"/></td>
</tr>
<tr>
<td>年龄</td>
<td><input type="text"name="age" id="age"></td>
</tr>
<tr>
<td>出生日期</td>
<td> <input type="date"name="birthday" id="birthday"/> </td>
</tr>
<tr>
<td>性别</td>
<td>
<input type="radio"name="sex" value="男">男
<input type="radio" name="sex" value="女">女
</td>
</tr>
<tr>
<td>电话号码</td>
<td><input type="text" name="tellphone" id="tellphone"></td>
</tr>
<tr>
<td><input type="submit" value="注册"></td>
</tr>
</table>
</form>
<br/>
<button id="btn">发起ajax请求</button>
</body>
</html>
处理器方法:
@RequestMapping(value = "/returnObject.do",method = RequestMethod.POST)
@ResponseBody
public user returnObject(user user){
return user;
}
原理代码分析:
<mvc:annotation-driver>注解驱动:就是创建实现HttpMessageConveter接口的七个实现类对象
注解驱动实现的功能是:完成java对象到json,xml,text,二进制等数据形式的转换,
实现这个转换的背后:HttpMessageConveter接口:消息转换器,定义了Java对象转换为数据格式的方法,这个接口有很多的实现类。
查看这个接口:
public interface HttpMessageConverter<T> {
boolean canRead(Class<?> var1, @Nullable MediaType var2);
boolean canWrite(Class<?> var1, @Nullable MediaType var2);
List<MediaType> getSupportedMediaTypes();
T read(Class<? extends T> var1, HttpInputMessage var2) throws IOException, HttpMessageNotReadableException;
void write(T var1, @Nullable MediaType var2, HttpOutputMessage var3) throws IOException, HttpMessageNotWritableException;
}
@RequestMapping(value = "/returnVoid.do",method = RequestMethod.POST)
public student Returnvod(HttpServletResponse response, String name,int age){
student stu = new student();
stu.setName(name);
stu.setAge(age);
return stu;
}
boolean canWrite(Class<?> var1, @Nullable MediaType var2);
void write(T var1, @Nullable MediaType var2, HttpOutputMessage var3);
canWriter作用:检查处理器方法的返回值,能不能转为var2表示的数据格式
检查student("李四",20)能不能转为var2表示的数据格式
可以转为json就返回true值
MediaType:表示数据格式的,内部有许多数据格式,例如json,xml等
write:把处理器方法的返回值对象,调用jackson中的ObjectMapper转为json字符串。
json = om.writeValueAsString(student)
@ResponseBody注解:
作用:把处理器方法返回的对象转为json后,通过HttpServletResponse输出给浏览器
位置:在处理器方法之上,和其他的注解没有顺序的关系
返回值List对象代码演示:
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2020/8/24
Time: 17:21
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<script type="text/javascript" src="js/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btn").click(function () {
$.ajax({
url:"returnObjectList.do",
type:"post",
dataType:"json",
success:function (data) {
//jQuery会把字符串转为json对象,赋值给data形参
$.each(data,function (i,n) {
alert(n.username+" "+n.age+" "+n.sex);
})
},
error:function () {
alert("error!!");
}
})
})
})
</script>
</head>
<body>
<button id="btn">发起ajax请求</button>
</body>
</html>
处理器方法:
@RequestMapping(value = "/returnObjectList.do",method = RequestMethod.POST)
@ResponseBody
public List<user> returnObjectList(){
List<user> users = new ArrayList<>();
user user1 = new user();
user1.setUsername("张三");
user1.setAge(21);
user1.setBirthday("2020-01-01");
user1.setSex("男");
user1.setTellphone("1302566566");
users.add(user1);
user1 = new user();
user1.setUsername("李四");
user1.setAge(22);
user1.setBirthday("2020-02-01");
user1.setSex("男");
user1.setTellphone("18164464467");
users.add(user1);
return users;
}