【问题标题】:spring mvc jquery ajax response as json encoding issuespring mvc jquery ajax响应作为json编码问题
【发布时间】:2012-09-06 13:55:27
【问题描述】:

最近我对来自服务器的 JSON 响应中的波兰字符有很大的问题。我对此有简单的 Ajax 请求:

jQuery.ajax( "/GetSimpleRuleList",
    {
        type:"GET",
        responseType:"application/json;charset=utf-8",
        contentType:"application/json;charset=utf-8",
        cache:false
    } ).done( function ( data )
    {
        console.log( data );
        //nevermind here
    } );

以及服务器端的适当控制器:

@RequestMapping(value = "/GetSimpleRuleList", method = RequestMethod.GET)
public
@ResponseBody
String getRuleList( ServletResponse response )
{
    //magically getting my list here
     response.setCharacterEncoding( "UTF-8" );
    return //Using JACKSON ObjectWriter here
}

现在我 100% 确定在服务器端和我从中获取数据的数据库上进行编码是可以的,这没问题。 但是当谈到从服务器读取响应时,它是:

???

而不是波兰字符,如:

ąćź

此外,它仅在接收到服务器的响应时失败,而发送带有数据的请求被正确编码。

在我的 web.xml 中,我有字符编码过滤器。

对此有什么帮助吗?我没有想法。

【问题讨论】:

标签: java jquery spring spring-mvc character-encoding


【解决方案1】:

现在我 100% 确定在服务器端和我从中获取数据的数据库上进行编码是可以的

如果您的响应中尚未出现 Content-Type 标头,请尝试添加它:

response.setHeader("Content-Type", "application/json;charset=UTF-8")

从数据库读取时确保使用 UTF-8 字符集。 Jackson 的编码默认为 UTF-8,所以你的数据可能没有使用 UTF-8 编码?!?

从数据库读取时使用什么编码?也许是 ISO-8859-2?

【讨论】:

    【解决方案2】:

    尝试将您的响应类型更改为 org.springframework.http.ResponseEntity

    public ResponseEntity<String> getRuleList(){
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.add("Content-Type", "application/json; charset=utf-8");
        responseHeaders.setCacheControl("no-cache, max-age=0"); 
        String allyourjson = "yourjsongoeshere";
        return new ResponseEntity<String>(allyourjson, responseHeaders, HttpStatus.OK);
    }
    

    【讨论】:

      【解决方案3】:

      您可以在控制器类上方使用 spring 注释 RequestMapping 来接收所有响应中的 application/json;utf-8

      @Controller
      @RequestMapping(produces = {"application/json; charset=UTF-8","*/*;charset=UTF-8"})
      public class MyController{
       ...
      @RequestMapping(value = "/GetSimpleRuleList", method = RequestMethod.GET)
      public
      @ResponseBody
      String getRuleList( ServletResponse response )
      {
          //magically getting my list here
           response.setCharacterEncoding( "UTF-8" );
          return //Using JACKSON ObjectWriter here
      }
       ...
      }
      

      【讨论】:

        猜你喜欢
        • 2011-10-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多