2014年3月27日 星期四

Spring MVC注解-@RequestBody(解決前端亂碼)

  • @RequestBody 將HTTP請求正文轉換为适合的HttpMessageConverter對象。
  • @ResponseBody 將內容或對象作为 HTTP 響應正文返回,並調用适合HttpMessageConverter的Adapter轉換對象,寫入輸出流。

這次是從Controller  送出 JSON 去前端 ,但發現在前端瀏覽器在顯示中文的時候都後亂碼

原本:

@RequestMapping(params = "action=queryMapDeviceList")
public void queryMapDeviceList(HttpServletRequest request,
HttpServletResponse response) throws IOException, Exception {

........................................................................省略

jsonObjectMaryT.put(new JSONObject(deviceDataT));
jsonObject.put("T", jsonObjectMaryT);

System.out.println("Tbreak =" + jsonObjectMaryT);
System.out.println("Toffline =" + jsonObjectMaryT);
PrintWriter out = response.getWriter();
   out.println(jsonObject.toString());
   out.flush();
   out.close();

}

後來使用@RequestBody 讓訊息出去時用HttpMessageConverter 所設定的格式出去

在mvc_dispatcher_servlet.xml :

<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/>
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" >
<property name="messageConverters">
         <list>
             <bean class = "org.springframework.http.converter.StringHttpMessageConverter">
                <property name = "supportedMediaTypes">
                      <list>
                          <value>text/html;charset=UTF-8</value>   
                     </list>
                </property>
             </bean>
         </list>
   </property>
  </bean>

在controller:

@RequestMapping(params = "action=queryMapDeviceList")
@ResponseBody
public String queryMapDeviceList(HttpServletRequest request,
HttpServletResponse response) throws IOException, Exception {

........................................................................

jsonObjectMaryT.put(new JSONObject(deviceDataT));
jsonObject.put("T", jsonObjectMaryT);

System.out.println("Tbreak =" + jsonObjectMaryT);
System.out.println("Toffline =" + jsonObjectMaryT);
PrintWriter out = response.getWriter();

return jsonObject.toString();
}

這樣問題就解決了,這送出去的String 都以UTF-8 送出!!



參考資料:
http://rritw.com/a/JAVAbiancheng/Spring/20120810/202602.html