2013-08-22 36 views
1

最近我正在開發一個新項目,UTF-8是必須的。我不知道我爲什麼要面對這個問題,但對我來說真的很陌生。我真的嘗試了我所知道的一切,但問題依然存在。無法解碼我的servlet中的西里爾字符串

我送一個JSON字符串到我的servlet和這裏是servlet部分:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
    response.setContentType("text/html; charset=UTF-8"); 
    response.setCharacterEncoding("UTF-8"); 
    request.setCharacterEncoding("UTF-8"); 
    if (action.equals("startProcess")) { 
     final String data = request.getParameter("mainData"); 
     URLDecoder.decode(data, "UTF-8"); 

     System.out.println("DATA \n" + URLDecoder.decode(data, "UTF-8")); 
     JSONObject jsonObj = new JSONObject(); 
     try { 


      JSONArray jsonArr = new JSONArray(URLDecoder.decode(data, "UTF-8")); 
      jsonObj.put("data", jsonArr); 
      JSONArray array = jsonObj.getJSONArray("data"); 
      System.out.println("insertDtls \n" + jsonObj.toString()); 

     } catch (Exception e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 


    } 
} 

System.out.println("insertDtls \n" + jsonObj.toString());回報:

這樣的結果:DATA [{"department":"1"},{"stampType":"кÑÑÐ³Ð»Ð°Ñ Ð¿ÐµÑаÑÑ"},{"headCompany":"да"},{"stampReason":"1"},{"textToPrint":"asd"},{"comments":"da"},{"other":"дÑÑгой"}]

我真的不知道在這裏做什麼。我確信我錯過了一些非常小的東西,但我無法發現它。有沒有可能讓這個字符串以某種方式進行雙重編碼?

+0

是什麼角色呢?拉丁語還是其他語言?我認爲你不能用System.out打印大多數語言。 – ahmedalkaff

+0

它是西里爾文。 – Slim

+0

當你將它寫入響應而不是控制檯時,你會得到什麼? – ahmedalkaff

回答

2

String data = request.getParameter("mainData");

的request.getParameter()已經解碼mainData參數。沒有進一步的解碼是必要的:URLDecoder.decode(data, "UTF-8")

如果仍想獲得原始mainData參數值使用request.getQueryString(),然後對其進行解碼:URLDecoder.decode(request.getQueryString(), "UTF-8");


在客戶端確保發送GET請求時,所有的URL參數正確的UTF-8編碼。 也在服務器端確保您的GET參數是UTF-8解碼。例如,要在Tomcat中解決它,你必須在server.xml中配置的URIEncoding屬性:
<Connector URIEncoding="UTF-8" connectionTimeout="20000" port="8080" protocol="HTTP/1.1" ...>

+2

提到'request.setCharacterEncoding()'只對POST請求參數有效並且設置響應內容類型和編碼對當前請求的參數完全沒有影響是有幫助的。 OP案例中的關鍵是在服務器配置('URIEncoding'等)中設置GET請求參數編碼。另請參閱[Unicode - 如何獲得正確的字符?](http://balusc.blogspot.com/2009/05/unicode-how-to-get-characters-right.html) – BalusC

-2

嘗試使用-Dfile.encoding = UTF-8參數運行您的java進程。