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










2014年1月26日 星期日

新手訓練班-越等練功-2

第二課 - 程式架構

先從RMI 下手

簡單了解一下 RMI

Remote Method Invocation :遠端方法叫用 -->Java 分散式系統設計中一個重要的基礎

RMI 架構圖


所以用RMI 架構 來規劃自己的程式架構









2014年1月24日 星期五

新手訓練班-越等練功-1

第一課

要做出如圖流程的一組小程式

Hibernate、RMI 沒聽過 也沒寫過.....ORZ

JDBC、Swing    有聽過,但沒寫過

所以第一步,當然是把他們弄清楚!!