0

I am doing a sample application for UTF-8 with Spring to support multi-language .

This is my JSP with Script ,

<%@ 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 type="text/javascript">
    var contexPath = "<%=request.getContextPath() %>";
      </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: contexPath + "/test.html",
            async: true,
            data: "intxnId=" + intxnId + "&message=" + encodeURIComponent(message),
            //dataType: "json",
            dataType: "html",
            contentType: "application/x-www-form-urlencoded; charset=utf-8",
            scriptCharset: "utf-8",
            success: function(response) {

            alert(response);
            alert(response.message);

            if (response !== null && response !== "" && response !== "null") {

                var txt = '{"data":[' + response + ']}';
                var json = eval("(" + txt + ")");
                for (i = 0; i < json.data.length; i++) {
                var data = json.data[i];

                var name = data.name;
                var message = data.message;
                var time = data.time;

                alert("Name : " + name + "\nMessage : " + message + "\ntime : " + time);
                var createHTML = send(name, message, time);
                $("#messageDisplayArea").append(createHTML);
                }
                ;
            }

            },
            error: function(e) {
            alert('Error: ' + e);
            },
        });

        function send(name , message , time){

            var user = "<div id='user' class='fontStyle'>"+name+"</div>";
            var msg = "<div id='msg'  class='fontStyle'>"+message+"</div>";
            var timeStamp = "<div id='time'  class='fontStyle'>"+time+"</div>";
            var row = "<div id='msgSet' >"+ user + msg + timeStamp +"</div>";

            return row;
        }
        }
    </script>
    </body>

</html>

My Spring controller will be ,

   @RequestMapping(value = "test.html", method=RequestMethod.POST , headers = "Accept=*",produces = "application/json; charset=utf-8")
   public @ResponseBody String sendMessage(HttpSession session, @RequestParam String intxnId, @RequestParam String message, HttpServletRequest request, HttpServletResponse response) {

    String contentType = "application/json; charset=utf-8";
        response.setContentType(contentType);
        try {
           // request.setCharacterEncoding("utf-8");
        request.setCharacterEncoding("application/json; charset=utf-8");

        } catch (Exception e) {
        e.printStackTrace();
        }
        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();
        }
    }
    return json;
    }

My Controllers prints ,

Send Message UTF-8 ----------------- தமிழ் அரிச்சுவடி
Send Message  :::::::: : {"message":"தமிழ் அரிச்சுவடி","time":"time","name":"test"}

In this my controller prints the local language . But in the JQuery success alert , I got message as ???? . I need to append the local language text in my JSP .

Hope our stack members will help me.

4

2 回答 2

0

I got the solution by changing the Controller as ,

    @RequestMapping(value = "test.html", method=RequestMethod.POST , headers = "Accept=*",produces = "application/json; charset=utf-8")
    public 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);
    }
于 2013-07-08T12:26:49.560 回答
0

以下代码应该可以解决您的问题。

   @RequestMapping(value="<your path>",produces = "application/json; charset=utf-8")    
    public @ResponseBody String sendMessage(@RequestParam String intxnId, @RequestParam String 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();
                }
            }
            return json;
            }

这将产生 UTF-8 ajax 响应。加入 mimeType:"application/json; charset=UTF-8"jQuery。

于 2013-07-08T09:35:52.707 回答