SpringMVC中@ResponseBody的相关注意点

博主习惯性用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的相关知识先说到这里,以后继续补充。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值