java - (Spring + JSP + jQuery-AJAX + JSON)设置环境的 UTF-8 问题?

标签 java jquery spring utf-8

我正在 java 中使用 Spring 3.x 做一个 chat 项目,它需要 多语言支持 .

这是我所做的。

我的 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">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

我的 web.xml 有:

<filter>
    <filter-name>characterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
        <param-name>forceEncoding</param-name>
        <param-value>true</param-value>
    </init-param>
</filter>

<filter-mapping>
    <filter-name>characterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

在我的 Tomcat server.xml 中有:

  <Connector (...) URIEncoding="UTF-8" />

我的Java环境有:

  JAVA_TOOL_OPTIONS     -Dfile.encoding=UTF8

在我的 Spring-controller 中有:

@RequestMapping(value="sendMessage.html",method=RequestMethod.POST)
public  @ResponseBody String sendMessage(HttpSession session,@RequestParam String intxnId,@RequestParam String message, HttpServletRequest request,HttpServletResponse response){

        String contentType= "text/html;charset=UTF-8";
        response.setContentType(contentType);
        //response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Type", "application/json; charset=UTF-8");
        try {
            request.setCharacterEncoding("utf-8");

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.setContentType("text/plain;charset=UTF-8"); 

        System.out.println("Send Message UTF-8 ----------------- "+ message);

    String json = null;
    BasicChatProtocol protocol = CustomerManagement.protocol.put(intxnId, chatProtocol.getProtocol());
    HashMap<String,String> result = send.send(message, intxnId, protocol);
    result.put("name",(String) session.getAttribute("nickName"));
    ObjectMapper map = new ObjectMapper();
    if(result.size()!= 0){
        try {
            json = map.writeValueAsString(result);
            result.clear();
            result = null;
            System.out.println("Send Message  :::::::: : "+json);
        } catch (Exception e) {
            e.printStackTrace();
        } 
    }
return json;

}

我的 jQuery-AJAX 将是:

function sendMessage(){
    var intxnId = $("#hide").val();
    var message = $("#message").val();
    alert("send  : \n intxnId : "+intxnId+"\nmessage : "+message);
    $.ajax({  
        type: "POST", 
        cache: false,
        url: contexPath + "/sendMessage.html",
        async:     true,
        contentType: "application/x-www-form-urlencoded; charset=utf-8",
        scriptCharset: "utf-8",
        dataType: 'html',
        data: "intxnId=" + intxnId +"&message="+ encodeURIComponent(message),

        success: function(response){

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

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

    }); 
}

但是当我发送本地语言消息அவர்களுக்கு(泰米尔语)时,alert box中只有??????? code> 和 查看页面

但是我在控制台中获得了 local language(SysOut in controller)并且所有 Special Characters 都可以使用。

注意:我认为我的 response from the controller 有问题。因为当我将 message 发送到 Controller 我在 javascript alert 中收到了 message as small boxes。但是当 response 来时,我在 alert box 中得到了 ?????

我的控制台打印,

Send Message UTF-8 ----------------- அவர்களுக்கு
Mesge what I send :::: அவர்களுக்கு
Send Message :::::::: : {"message":"அவர்களுக்கு","time":"time","name":"Human"}

我不知道我错过了什么。

注意:我没有使用任何数据库

希望我们的堆栈用户能提供更好的解决方案。好的答案绝对值得赞赏。

最佳答案

我已经用这个测试 Controller 尝试过你的 javascript:

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

它就像一个魅力,我在使用 chrome 浏览器的警报弹出窗口中看到响应中的 UTF-8 字符。

我的 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>

关于java - (Spring + JSP + jQuery-AJAX + JSON)设置环境的 UTF-8 问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17421645/

相关文章:

java - 如何在 gwt 中使字符串内的 url 可点击

java - 基于当前日期+时间查询 JPA 实体实例的最佳方法是什么?

javascript - 使用 d3 Nest 从 csv 创建下拉/选择列表

java - 在 Spring 过滤器中更改 HttpServletRequest 的 POST 主体

java - 使用 Spring JDBCTemplate 设置 Tomcat JDBC 连接池

java - 获取数组错误消息

java - 我的客户需要什么才能使用我的 Java 程序? (i文本)

javascript - 使用单个函数更新多个div的charcount

jquery - jqPlot 缩放图 31 天

java - 通过 Web 服务公开网站