I have read through the post "Who sets response content-type in Spring MVC (@ResponseBody)", it helped me to resolve my problem of displaying UTF-8 (CJK characters) data at client side using JSON method.
Now find I have problem to post UTF-8 data to server side using JSON. The javascript method I am using:
function startSomething() {
console.log("startSomething()");
console.log(" getOriginName() = " + getOriginName());
console.log(" getDestinationName() = " + getDestinationName());
$.ajaxSetup({ scriptCharset: "utf-8" ,
contentType: "application/json; charset=utf-8"});
// send the data to server side
$.ajax({
url: "/mywebapp/something/start",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: {
originName : getOriginName(),
destinationName : getDestinationName()
},
success: function(response) {
// do something
}
});
}
After triggering the javascript method, I can see the value printed out in browser console correctly, something as:
getOriginName() = N Bridge Rd
getDestinationName() = 夢幻之城@ Boat Quay
My server side code:
@RequestMapping("/something")
@Controller
public class TestController {
// the logger
private Logger logger = Logger.getLogger(TestController.class);
@RequestMapping(value = "/start", method = RequestMethod.GET)
public ResponseEntity<String> start(@RequestParam String originName,
@RequestParam String destinationName,
HttpServletRequest request,
HttpServletResponse response) {
String characterEncoding = request.getCharacterEncoding();
String contentType = request.getContentType();
logger.debug(" characterEncoding = " + characterEncoding);
logger.debug(" contentType = " + contentType);
if (logger.isDebugEnabled()) {
String logMessage = StringUtils.join(
new Object[]{
" originName = ", originName,
" destinationName = ", destinationName
}
);
logger.debug(logMessage);
}
...
}
}
The output from my server side code:
TestController - characterEncoding = UTF-8
TestController - contentType = application/json; charset=utf-8
TestController - originName = N Bridge Rd destinationName = 夢幻ä¹å@ Boat Quay
You can see that the request encoding is UTF-8, but the value from client side is wrongly encoded CJK character.
What can go wrong here? Please give me some hints, thank you. George