springMvc配置xml使ResponseBody返回Json


@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 夏德旺


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM