1. 程式人生 > >Spring MVC的@ResponseBody返回JSON串

Spring MVC的@ResponseBody返回JSON串

Xml程式碼 
<bean class ="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" >      <property name="messageConverters">    <list>     <ref bean="mappingJacksonHttpMessageConverter" /><!-- json轉換器 -->    </list>  </property>  </bean>      

<bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />  <bean class ="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" >     <property name="messageConverters">   <list> 
   <ref bean="mappingJacksonHttpMessageConverter" /><!-- json轉換器 -->   </list> </property> </bean>   <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" /> 
需要以下兩個jar包: 

Xml程式碼 
<dependency org="org.codehaus.jackson" name="jackson-core-asl" rev="1.5.5" conf="runtime->default" />  

<dependency org="org.codehaus.jackson" name="jackson-mapper-asl" rev="1.5.5" conf="runtime->default" />  

<dependency org="org.codehaus.jackson" name="jackson-core-asl" rev="1.5.5" conf="runtime->default" /> 
<dependency org="org.codehaus.jackson" name="jackson-mapper-asl" rev="1.5.5" conf="runtime->default" /> 



Java程式碼 
@RequestMapping(value="/nogood", method=RequestMethod.GET)   
public @ResponseBody CmUser execute(String userid) {   
  CmUser u = new CmUser();   
  u.setAge(16);   
  u.setName("測試使用者");   
  return u;   
}  



通過上面的程式碼可以實現java物件直接可以轉json物件,下面是專案中的配置

    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="webBindingInitializer">
            <bean class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
                <property name="conversionService" ref="conversionService"/>
            </bean>
        </property>
        <property name="messageConverters">
            <list>
                <bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter" />
                <bean class="org.springframework.http.converter.StringHttpMessageConverter" >
                    <property name = "supportedMediaTypes">
                           <list>
                                   <value>text/plain;charset=UTF-8</value>
                          </list>
                     </property> 
                </bean>
                <bean class="org.springframework.http.converter.ResourceHttpMessageConverter" />
                <!-- 注:開啟此類需相關jar包持:javax.xml.bind.JAXBException
                <bean class="org.springframework.http.converter.xml.SourceHttpMessageConverter" />
                <bean class="org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter" />
                <bean class="org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter" />
                 -->
                <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
            </list>
        </property>
    </bean>

下面分析@ResponseBody 註解

在SpringMVC中可以在Controller的某個方法上加@ResponseBody註解,表示該方法的返回結果直接寫入HTTP response body中。

但是實際使用中發現最後生成的response中"Content-Type"的值不正確

Spring使用AnnotationMethodHandlerAdapter來處理@ResponseBody,該類再使用一些HttpMessageConverter來具體處理資訊。

AnnotationMethodHandlerAdapter使用request header中"Accept"的值和messageConverter支援的MediaType進行匹配,然後會用"Accept"的第一個值寫入 response的"Content-Type"。

一般的請求都是通過瀏覽器進行的,request header中"Accept"的值由瀏覽器生成。

Chrome生成的值為application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5

IE8生成的值為application/x-ms-application, image/jpeg, application/xaml+xml, image/gif, image/pjpeg, application/x-ms-xbap, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*

所以最後寫入response中"Content-Type"的值為"application/xml"或"application/x-ms-application"。

但我們一般會在標註@ResponseBody的方法上返回String或byte[]型別的結果,期望的"Content-Type"的值應為"text/plain"或"application/octet-stream"。

這樣導致了瀏覽器不能正確處理返回的內容。

實際上Spring在用HttpMessageConverter處理的過程中首先會判斷response header中有沒有寫入"Content-Type",如果沒有寫入的話才會使用request header中"Accept"的第一個值。

但是由於Spring對HttpServletResponse進行了封裝,實際上使用的是ServletServerHttpResponse,這個類有一個對真正的HttpServletResponse的引用。

判斷response header的過程中使用的是ServletServerHttpResponse的getHeaders()方法,但該方法並沒有返回真正的HttpServletResponse中的header。(這應該有問題吧?)

所以我們雖然可以在Controller的方法中加入對HttpServletResponse的引用,然後設定"Content-Type"的值,但是並不會起作用。

通過上面的分析,@ResponseBody看來是無法使用了。

還可以參考下面文章:http://www.iteye.com/topic/1124054
http://www.360doc.com/content/12/0809/11/9600761_229177035.shtml

相關推薦

Spring MVC的@ResponseBody返回JSON

Xml程式碼 <bean class ="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" >      <property name="mess

Spring MVC的@ResponseBody返回JSON時Content-Type編碼問題

Xml程式碼 <bean class ="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" >      <property name="messa

解決Spring MVC @ResponseBody返回中文字符亂碼問題

有效 per log bean dia media converter 原因 ons 引起亂碼原因為spring mvc使用的默認處理字符串編碼為ISO-8859-1 具體參考org.springframework.http.converter.StringHttpMess

Spring中@ResponseBody 返回json字串date型別變成long型的問題

以前,關於返回json字串date型別變成long(時間戳)型別,一直存在困難,兩個方面,1,通過前端的格式轉化;2,同事date轉成string型別,再做傳值,如此既降低編碼效率又不利於全端開發人員的工作負擔。為此今天做如下總結; 第一步:設計組價 p

Spring MVC返回JSON資料的幾種方式

我們都知道Spring MVC 的Controller方法中預設可以返回ModeAndView 和String 型別,返回的這兩種型別資料是被DispatcherServlet拿來給到檢視解析器進行繼續處理返回頁面的,而不是直接返回給客戶端的。有時候我們需要發請求後讓服務端直接返回一些資料,不再經過Dispa

Spring MVC返回JSON數據的幾種方式

return res set 轉換 public servlet 兩種 dispatch ont 我們都知道Spring MVC 的Controller方法中默認可以返回ModeAndView 和String 類型,返回的這兩種類型數據是被DispatcherServlet

Spring mvc + jackson2 返回json格式(包含日期格式解析)

寫了那麼多,發現白忙活了一場,原來jackson也有一個@JsonFormat註解,將它配置到Date型別的get方法上後,jackson就會按照配置的格式轉換日期型別,而不自定義轉換器類,欲哭無淚啊。辛苦了那麼多,其實別人早已提供,只是沒有發現而已。 不說了,直接上方

spring mvc如何返回json資料

springmvc如何返回json資料 常用的方法有兩種: 1.利用Gson等json轉換工具,將物件轉換成json字串,並通過HttpServletResponse將json字串返回給前臺 @RequestMapping("/getJson1")

Spring MVC返回Json陣列資料

建立User package com.po; public class User { private String userName; private String passWord; publ

解決Spring MVC @ResponseBody返回中文字串亂碼問題

引起亂碼原因為spring mvc使用的預設處理字串編碼為ISO-8859-1, 具體參考org.springframework.http.converter.StringHttpMessageConverter類中public static final Charset D

spring 4.x下讓http請求返回json

當前很多應用已經開始將響應返回為json串,所以基於springframework框架開發的服務端程式,讓響應返回json字串成為了一種常用手段。 這裡介紹一下如何在spring-MVC框架下方便快捷的返回json字串。 首先,需要在controller類的方法名頭上加@R

Spring MVC 介面返回json資料過濾空值

前後端互動時,後端返回給前端是一個json,json中的值是由一個物件轉換而來的,有時候該物件中可能某些欄位的值是空,返回給前端的json就會出現某些key的value是空,在默寫情況下不利於前端處理。 其實在後端返回時可以進行資料過濾,將物件是為空的欄位自動過濾掉。一行程

Spring MVC 前後臺傳遞json格式數據 Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported

support style logs ica spring enc json格式數據 分享 技術 報錯如下: Content type ‘application/x-www-form-urlencoded;charset=UTF-8‘ not supported

Spring MVC中傳遞json數據時顯示415錯誤解決方法

ping 數據 value 解決方法 傳遞 ica ons pub eth 在ajax中設置 ContentType為‘application/json;charset=utf-8‘ 傳遞的data類型必須是json字符串類型:{“key”:"va

Python3.x:訪問帶參數鏈接並且獲取返回json

ada utf callback ear live from python3 mini body Python3.x:訪問帶參數鏈接並且獲取返回json串 核心代碼: import json import xml.dom.minidom from urllib impor

SpringMVC 使用@ResponseBody返回json 中文亂碼

AI ngs target err bstr .html -s 找到 html   有時候我們發現接收的是中文,返回卻是個?。這確實是個蛋疼的問題,Spring中解析字符串的轉換器默認編碼居然是ISO-8859-1 /** * Implementation of

SSM框架:解決後臺傳數據到前臺中文亂碼問題,使用@ResponseBody返回json 中文亂碼

tex 多人 AC 文件 進行 orm clas sha pes 場景: 在實際運用場景中,當前臺發起請求後,我們需要從後臺返回數據給前臺,這時,如果返回的數據中包含中文,則經常會出現在後臺查詢出來都是好好,但是傳輸回去就莫名的亂碼了,而且,我們明明已經在 web.xml

Spring MVC —— 前後臺傳遞JSON

後臺 print col 方法 http .ajax AS RR map 1. 傳遞JSON參數 vardata = {‘id‘:1,‘name‘:‘abc‘}; $.ajax({ type:‘post‘, url:‘homePageAction.do?t

Spring mvc,jQuery和JSON資料互動

一、實驗環境的搭建 1、Spring mvc jar。 匯入spring mvc執行所需jar包。匯入如下(有多餘)     2、json的支援jar       3、加入jQuery。

Spring Boot @ResponseBody 轉換 JSON資料時Date 型別處理方法

引用處: https://blog.csdn.net/molashaonian/article/details/53025118 https://blog.csdn.net/henianyou/article/details/81945409   解析JSON的方式: