Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bad encoding when returning a string using Spring MVC & ajax

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

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

In my web page I'm declaring

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

That's my controller:

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

   return str;
}

And my ajax request:

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

Any ideas what am I doing wrong here?

like image 245
koela1 Avatar asked Mar 04 '13 15:03

koela1


1 Answers

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

jQuery style - mimeType:

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

Vanilla 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:

  1. 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.
  2. 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;
}

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

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:

  • web-container supports this properly
  • response's character encoding is UTF-8
  • AJAX request character encoding is also UTF-8
like image 113
n1ckolas Avatar answered Nov 10 '22 07:11

n1ckolas