(Spring + JSP + jQuery-AJAX + JSON ) setting environment for UTF-8 issue?

前端 未结 3 1759
盖世英雄少女心
盖世英雄少女心 2021-02-20 14:21

I am doing a chat project in java with Spring 3.x which needs Multi-language support.

Here is what I have done.

相关标签:
3条回答
  • 2021-02-20 14:34

    I would try some debugging in the browser. Use some developer tools in your browser (Developer Tools in Chrome, Firebug extension for Firefox or any other such tool in any other browser) and try to check HTTP response you are getting for your ajax - check if HTTP headers are correctly set (utf8 encoding, etc.) and maybe if ypur special characters are displayed correctly there - so you can see, if you are getting correct answer from the server.

    BTW - I dont see any error in code you posted, everything looks good. Just double check, that page on that you are displaying response with ajax, has utf8 encoding set...

    0 讨论(0)
  • 2021-02-20 14:38

    I have tried your javascript with this test controller:

    @Controller
    public class TestController {
        @RequestMapping(value = "/test", method = POST, produces = "application/json; charset=utf-8")
        public @ResponseBody
        ResponseEntity<String> sendMessage(HttpSession session, @RequestParam String intxnId, @RequestParam String message, HttpServletRequest request, HttpServletResponse response) {
    
            System.out.println("Send Message UTF-8 ----------------- " + message);
    
            String json = null;
            HashMap<String, String> result = new HashMap<String, String>();
            result.put("name", "test");
            result.put("message", message);
            result.put("time", "time");
            ObjectMapper map = new ObjectMapper();
            if (!result.isEmpty()) {
                try {
                    json = map.writeValueAsString(result);
                    System.out.println("Send Message  :::::::: : " + json);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            HttpHeaders responseHeaders = new HttpHeaders(); 
            responseHeaders.add("Content-Type", "application/json; charset=utf-8"); 
            return new ResponseEntity<String>(json, responseHeaders, HttpStatus.CREATED);
        }
    }
    

    It works like a charm, and I see UTF-8 characters from the response in the alert popup, using chrome browser.

    My test.jsp:

    <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
    <%request.setCharacterEncoding("UTF-8");%>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        </head>
        <body>
            <h1>Test</h1>
            <input type="text" id="hide" />
            <input type="text" id="message"/>
            <button id="button">test</button>
            <div id="messageDisplayArea"></div>
    
    
            <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
            <script>
            $('#button').on('click', sendMessage);
    
            function sendMessage() {
                var intxnId = $("#hide").val();
                var message = $("#message").val();
                alert("send  : \n intxnId : " + intxnId + "\nmessage : " + message);
                $.ajax({
                    type: "POST",
                    cache: false,
                    url: "${pageContext.request.contextPath}/test",
                    async: true,
                    data: "intxnId=" + intxnId + "&message=" + encodeURIComponent(message),
                    success: function(response) {
    
                        if (response !== null && response !== "" && response !== "null") {
                            alert("Name : " + response.name + "\nMessage : " + response.message + "\ntime : " + response.time);
                            $("#messageDisplayArea").append(message);
                        }
    
                    },
                    error: function(e) {
                        alert('Error: ' + e);
                    },
                });
            }
        </script>
        </body>
    
    </html>
    
    0 讨论(0)
  • 2021-02-20 14:43

    Can you try using produces = "text/plain;charset=UTF-8" in the @RequestMapping

    @RequestMapping(value = "/test", method = POST, produces = "text/plain;charset=UTF-8")
        public @ResponseBody
    

    also check this: UTF-8 encoding problem in Spring MVC

    0 讨论(0)
提交回复
热议问题