欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Springmvc ResponseBody響應(yīng)json數(shù)據(jù)實現(xiàn)過程

 更新時間:2020年10月26日 11:29:15   作者:Y_wee  
這篇文章主要介紹了Springmvc ResponseBody響應(yīng)json數(shù)據(jù)實現(xiàn)過程,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下

該注解用于將 Controller 的方法返回的對象,通過 HttpMessageConverter 接口轉(zhuǎn)換為指定格式的數(shù)據(jù)如:json,xml 等,通過 Response 響應(yīng)給客戶端

示例

需求:使用@ResponseBody 注解實現(xiàn)將 controller 方法返回對象轉(zhuǎn)換為 json 響應(yīng)給客戶端。

前置知識點:Springmvc 默認(rèn)用 MappingJacksonHttpMessageConverter 對json數(shù)據(jù)進(jìn)行轉(zhuǎn)換,需要加入jackson 的包。

注:2.7.0以下的版本用不了

jsp代碼

<!-- 測試異步請求 --> 
<input type="button" value="測試ajax請求json和響應(yīng)json" id="testJson"/>

<script type="text/javascript"src="${pageContext.request.contextPath}/js/jquery.min.js"></script> 
<script type="text/javascript">
$(function(){
	$("#testJson").click(function(){
    $.ajax({
      type:"post",
      url:"${pageContext.request.contextPath}/testResponseJson",
      contentType:"application/json;charset=utf-8",
      data:JSON.stringify({"id":1,"name":"test","money":999.0}),
      dataType:"json",
      success:function(data){
      	alert(data);
			}
		});
	});
})
</script>

控制器代碼

/**
* 響應(yīng) json 數(shù)據(jù)的控制器
* @author 黑馬程序員
* @Company http://www.ithiema.com
* @Version 1.0
*/
@Controller("jsonController")
public class JsonController {
  /**
  * 測試響應(yīng) json 數(shù)據(jù)
  */
	@RequestMapping("/testResponseJson")
	public @ResponseBody Account testResponseJson(@RequestBody Account account) {
    System.out.println("異步請求:"+account);
    return account; 
	} 
}

配置json轉(zhuǎn)換器

如果不使用注解驅(qū)動<mvc:annotation-driven />,就需要給處理器適配器配置json轉(zhuǎn)換器

在springmvc.xml配置文件中,給處理器適配器加入json轉(zhuǎn)換器:

<!--處理器適配器 -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
  <property name="messageConverters">
  	<list>
  		<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
  	</list>
  </property>
</bean>

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論