您的位置:首页 > 编程语言 > Java开发

SpringMVC中@ResponseBody的相关注意点

2015-12-09 15:05 363 查看
博主习惯性用SpringMVC的@ResponseBody注解返回JSON字符串,原先采用的方法是GSON将对象转换成json字符串。(需要引入gson-2.x.x.jar的jar包)

@ResponseBody
@RequestMapping(value = "/cpuUsage.do", produces = "text/html;charset=UTF-8")
public String getCpuUsage(@RequestParam(value = "name", required = true) String clusterName)
{
logger.info("/charts/cluster/cpuUsage.do?name=" + clusterName);
String ans = null;
try
{
ans = clusterChartsService.getCpuUsage(clusterName);
logger.info(ans);
}
catch (InstantiationException | IllegalAccessException | RuntimeFaultFaultMsg | DatatypeConfigurationException
| NullPointerException | ConnectException | XMLStreamException e)
{
logger.error(e.getMessage());
}
return ans;
}
如上代码所示,Controller的返回值就为String类型。

在getCpuUsage()方法中:

public String getCpuUsage(String clusterName) throws RuntimeFaultFaultMsg, DatatypeConfigurationException,
InstantiationException, IllegalAccessException, ConnectException, XMLStreamException
{
double value = MoniterWsInterface.getClusterCpuUsageByClusterName(clusterName);
Charts charts = new Charts(value, new Date());
String ans = Gson.class.newInstance().toJson(charts);

return ans;
}
采用Gson将对象转换成JSON字符串,然后返回给前端调用。

但是有些读者可能了解到Spring的@ResponseBody可以自动将对象转换为JSON对象然后返回给前端,这里项目中需要加入两个jar包:jackson-core-asl-1.9.x.jar和jackson-mapper-asl-1.9.x.jar。然后在springMVC的配置文件中加入:

<mvc:annotation-driven />


这句即可,也可以显示的标注,即在springMVC的配置文件中加入:

<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<ref bean="mappingJacksonHttpMessageConverter" />
</property>
</bean>
<bean id="mappingJacksonHttpMessageConverter"
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>
这样就可以采用@ResponseBody注解自动将对象(包括普通对象,List对象,Map对象等)转换为JSON.

@RequestMapping("/test.do")
@ResponseBody
public List<String> test(){
List<String> list = new ArrayList<String>();
list.add("zzh1");
list.add("zzh1");
list.add("zzh2");
list.add("字符串");
return list;
}
如上代码可以看到直接返回一个List的对象,这里springMVC的@ResponseBody标签会自动采用jackson讲对象转换为JSON。

这里有个小坑。在@ResponseBody注解上面还有一个@RequestMapping注解,有时候需要显示的标注一些信息,如:

@RequestMapping(value = "/test.do", produces = "application/json;charset=UTF-8")
如果这里的produces=“text/html,charset=UTF-8”就会报错:HTTP406的错误。所以这里要特别的小心。

好了@ResponseBody的相关知识先说到这里,以后继续补充。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: