Slim
Slim

Reputation: 1744

Can not decode a cyrillic string in my servlet

Recently I'm working on a new project and UTF-8 is a must. I don't know why I'm facing this, but it is really strange to me. I really tried everything I knew, but the problem remains.

I'm sending a JSON string to my servlet and here is the servlet part:

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();
        }


    }
}

the System.out.println("insertDtls \n" + jsonObj.toString()); returns:

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

I realy don't know what to do here. I'm sure that I'm missing something really small, but I'm not able to spot it. Is it possible to have this string double encoded somehow?

Upvotes: 3

Views: 3596

Answers (2)

Sergej Panic
Sergej Panic

Reputation: 839

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

request.getParameter() already decodes mainData parameter. No further decoding is necessary: URLDecoder.decode(data, "UTF-8")

If you still want to get raw mainData parameter value use request.getQueryString() and then decode it: URLDecoder.decode(request.getQueryString(), "UTF-8");


On client side make sure that when sending a GET request all URL parameters are correctly UTF-8 encoded. Also on server side make sure your GET parameters are UTF-8 decoded. For example to fix it in Tomcat you must configure URIEncoding attribute in server.xml:
<Connector URIEncoding="UTF-8" connectionTimeout="20000" port="8080" protocol="HTTP/1.1" ...>

Upvotes: 3

dvsander
dvsander

Reputation: 105

Try running your java process with the -Dfile.encoding=UTF-8 parameter.

Upvotes: -2

Related Questions