N
N
Nikolay Baranenko2017-06-14 21:37:45
JavaScript
Nikolay Baranenko, 2017-06-14 21:37:45

How to solve encoding problem when POST JSON to servlet?

Hello.

in java script ajax request send JSON using POST method

var json=[{"FUNCTION_GROUP":"Футбол"},{"FUNCTION_GROUP":"Шахматы"},{"FUNCTION_GROUP":"Плавание"}];
        $.ajax({
            type: 'POST',
            url: 'employees',
            data: JSON.stringify(json),
            success: function(data) {
                console.log( "Данные зафиксированы успешно.");
                },
            error: function(data) {
                console.log( "Отправка данных завершилась завершилась ошибкой: ");
        },
            contentType: "application/json",
            dataType: 'json'
        });


shipping details

Request URL:http://localhost:8000/employees
Request Method:POST
Status Code:200 
Remote Address:[::1]:8000
Response Headers
view source
Content-Length:97
Date:Wed, 14 Jun 2017 18:19:20 GMT
Request Headers
view source
Accept:application/json, text/javascript, */*; q=0.01
Accept-Encoding:gzip, deflate, br
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:97
Content-Type:application/json
Host:localhost:8000
Origin:http://localhost:8000
Referer:http://localhost:8000/LoginUser
User-Agent:Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36
X-Requested-With:XMLHttpRequest
Request Payload
view source
[{FUNCTION_GROUP: "Футбол"}, {FUNCTION_GROUP: "Шахматы"}, {FUNCTION_GROUP: "Плавание"}]
0
:
{FUNCTION_GROUP: "Футбол"}
1
:
{FUNCTION_GROUP: "Шахматы"}
2
:
{FUNCTION_GROUP: "Плавание"}


below code is java servlet a which accepts POST request and process json

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        StringBuilder sb = new StringBuilder();
        BufferedReader br = request.getReader();
        String str;
        while( (str = br.readLine()) != null ){
            sb.append(str);
        }
        try {
            JSONObject jObj = new JSONObject(sb.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        System.out.println(sb.toString());
        response.getWriter().append(sb.toString());
   }


ajax posts the data, BUT if you look at the result of the response in the browser, then the Cyrillic alphabet becomes abracadabra

[{"FUNCTION_GROUP":"Ðарды"},{"FUNCTION_GROUP":"Шахматы"},{"FUNCTION_GROUP":"ОБЖ"}]


How to solve this problem?

ps I tried to additionally wrap encodeURI(JSON.stringify(json)) in AJAX JSON
BUT in this case I get an exception in the servlet that JSON does not start with {, I suspect that the encoding after encodeURI is not restored....

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Sobko, 2017-06-14
@drno-reg

Try specifying response.setContentType("application/json; charset=utf-8");

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question