Bad encoding when returning a string using Spring MVC & ajax
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:
- 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;}
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