在开发网页得时候,我们可以通过将数据库中的一条信息映射到一个java类的一个对象来获取我们数据库中的内容,但是别人如果想获取我们的数据 他们并不知道里面是什么格式,所有在获取的时候可以通过json对象获取数据,获取出来的是一个json字符串
在之前我们用http返回json对象的时候
Gson类里面的toJson()方法可以将一个java’对象转化成一个json对象
public void userList(HttpServletResponse response) {
List<SysUserInfo> ul = userService.getUserList();
String userGson = new Gson().toJson(ul);
System.out.println(userGson);
try {
response.getWriter().write(userGson);
} catch (IOException e) {
e.printStackTrace();
}
}
在我们学习完mvc之后,可以不用这种麻烦的方法 可以通过@ResponseBody 标签的方法去转化
但是用这种方法 要在mvc里面配置一个转换器
也就是在mvc 的xml配置文件中 添加代码<mvc:annotation-driven></mvc:annotation-driven>
这个标签里面还可以加上属性(固定格式)
<mvc:annotation-driven>
<mvc:message-converters>
<!-- register-defaults="true"表示使用默认的消息转换器 -->
<!-- FastJson(Spring4.2x以上版本设置) -->
<!-- 使用@responsebody注解并且返回值类型为String时,返回的string字符串带有双引号"{'user':'songfs'}",其原因是直接将string类型转成了json字符串,应该在json解析器之前添加字符串解析器-->
<bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
<!-- FastJsonHttpMessageConverter4 使@ResponseBody支持返回Map<String,Object>等类型,它会自动转换为json-->
<!-- 需要返回json时需要配置 produces = "application/json"。不需要再指定utf-8了 -->
<bean id="fastJsonHttpMessageConverter" class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<!-- 加入支持的媒体类型 -->
<property name="supportedMediaTypes">
<list>
<!-- 这里顺序不能反,一定先写text/html,不然IE执行AJAX时,返回JSON会出现下载文件 -->
<value>text/html;charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
<value>application/xml;charset=UTF-8</value>
</list>
</property>
<property name="fastJsonConfig">
<bean class="com.alibaba.fastjson.support.config.FastJsonConfig">
<property name="features">
<list>
<value>AllowArbitraryCommas</value>
<value>AllowUnQuotedFieldNames</value>
<value>DisableCircularReferenceDetect</value>
</list>
</property>
<property name="dateFormat" value="yyyy-MM-dd HH:mm:ss"/>
</bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
@RequestMapping("userWs")
@ResponseBody //加上该标签 mvc会把返回给用户的java对象转化为json对象
public SysUserInfo userWs(){
return userService.getUserList().get(0);
}
注解用于将Controller的方法返回的对象,通过springmvc提供的 HttpMessageConverter接口转换为指定格式的数据如:json,xml等,通过Response响应给客户端
@RequestBody标签是将json对象转化为java对象得
在传入参数得时候 在参数定义前面加上@RequestBody标签 会自动将json对象转化为java对象