返回使用Spring MVC&放一个字符串时,错误编码;阿贾克斯字符串、错误、Spring、MVC

2023-09-11 01:02:11 作者:凉心的人却会说暖心的话

我有一个网页,要求使用Ajax希伯来字符串,但该字符串返回为??????

I have a web page that requests an hebrew string using Ajax but the string is returned as '??????'

奇怪的是,插入相同字符串的页面使用JSTL而不是Ajax时,它被正确显示...

The weird thing is that when inserting that same string to the page using JSTL and not Ajax, it is shown correctly...

在我的网页我声明了

<%@ page contentType="text/html" pageEncoding="UTF-8"%>

这是我的控制器:

@RequestMapping("get_label")   
public @ResponseBody String getLabel()
{
   String str = "בדיקה";

   return str;
}

和我的Ajax请求:

$.ajax({
    url:    "get_label",
    success:    function(result)
    {
        alert(result);
        $("#parameter_select label").text(result);
    }
});

任何想法,我究竟做错了什么?

Any ideas what am I doing wrong here?

推荐答案

这是因为AJAX的调用默认使用浏览器的默认编码(FE ANSI)。对于重写此,你需要做的:

This happens because AJAX-calls by default use browser's default encoding (f.e. ANSI). For overriding this you need to do:

jQuery的风格 - MIMETYPE

jQuery style - mimeType:

$.ajax({
    url:    "get_label",
    mimeType:"text/html; charset=UTF-8",
    success:    function(result)
    {
        alert(result);
        $("#parameter_select label").text(result);
    }
});

香草JS style:

xhr.overrideMimeType("text/html; charset=UTF-8")

但是,从另一方面,你需要确认,该服务器也将返回适当的响应。为此,您需要检查以下内容:

But from the other hand you need to be sure, that server also returns appropriate response. For this you need to check the following:

添加UTF-8支持的Web容器(如Tomcat)的与添加的的URIEncoding =UTF-8作为您的连接在 server.xml中设置;检查this了解更多信息。 如果previous变化并没有帮助(虽然它有),还请确保,即servlet响应的字符集也是 UTF-8 Add UTF-8 support for web-container (i.e. Tomcat) with adding URIEncoding="UTF-8" for your Connector settings in server.xml; check this for more information. If previous change didn't help (though it has to), please also make sure, that servlet response's character set is also UTF-8.

有关这一点,你可以使用显式的方法调用:

For this you can use either explicit call of method:

@RequestMapping("get_label")
public @ResponseBody String getLabel(HttpServletResponse response)
{
    String str = "בדיקה";

    //set encoding explicitly
    response.setCharacterEncoding("UTF-8");

    return str;
}

或者,这似乎是更preferable为 @ResponseBody 和Spring 3.1 +:

Or, which seems to be more preferable for @ResponseBody and Spring 3.1+:

@RequestMapping(value = "get_label", produces = "text/html; charset=UTF-8")
public @ResponseBody String getLabel(HttpServletResponse response)
{
    String str = "בדיקה";

    return str;
}

作为一个结论,我想澄清一下,对于AJAX的呼叫使用UTF-8编码的妥善处理,你必须确保,即:

As a conclusion I would like to clarify, that for proper handling of AJAX-calls with UTF-8 encoding, you have to make sure, that:

在网络容器支持这个正确 在响应的字符编码​​是UTF-8 在AJAX请求字符编码也是UTF-8