xiadewang

@ResponseBody

 

      在返回的数据不是html标签的页面,而是其他某种格式的数据时(如json、xml等)使用;

不在springMvc中配置json的处理的话,我们通常会在Controller层中获取到数据之后进行类型转化,将数据转成json字符串,比如调用fastjson进行转化,如下

@RequestMapping("/getCategoryTree")
	@ResponseBody
	public String getmCategoryTree() {
		String data = JSON.toJSONString(categoryService.getCategoryList());
		return data;
	}



这样的话,当我们有很多需要返回json数据的时候,就在每个方法中都要写一次转化然后再返回,下面通过在springmvc的xml配置文件中进行配置,可以省去以后代码中的转化操作

 

配置如下

 

	
	<bean id="jsonConverter"
		class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></bean>
	<bean
		class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
		<property name="messageConverters">
			<list>
				<ref bean="jsonConverter" />
			</list>
		</property>
	</bean>

注意此配置还需要在pom.xml文件中导入

		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.5.4</version>
		</dependency>


此时再看看Controller层中的代码

 

 

	@RequestMapping("/getCategoryTree")
	@ResponseBody
	public List<Category> getCategoryTree() {
		return categoryService.getCategoryList();
	}


此时就没有了json转化的那步操作了,但是注意此时的返回结果不再是String类型,而是要保持与service层中的返回类型一致。

 

created by 夏德旺

相关文章: