我已经阅读了帖子“Who sets response content-type in Spring MVC (@ResponseBody)”,它帮助我解决了使用JSON方法在客户端显示UTF-8(CJK字符)数据的问题。
现在发现我在使用 JSON 将 UTF-8 数据发布到服务器端时遇到问题。我正在使用的javascript方法:
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
}
});
}
触发javascript方法后,我可以看到浏览器控制台中正确打印出的值,如下所示:
getOriginName() = N Bridge Rd
getDestinationName() = 夢幻之城@ Boat Quay
我的服务器端代码:
@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);
}
...
}
}
我的服务器端代码的输出:
TestController - characterEncoding = UTF-8
TestController - contentType = application/json; charset=utf-8
TestController - originName = N Bridge Rd destinationName = 夢幻ä¹å@ Boat Quay
可以看到请求编码是UTF-8,但是客户端返回的值是错误编码的CJK字符。
这里可能会出现什么问题?请给我一些提示,谢谢。 乔治
最佳答案
我在 JSON 和 Spring 方面遇到了类似的问题,并通过指定 URIEncoding="UTF-8"
解决了该问题。上<Connector>
在我的 Tomcat server.xml 配置中,如下所述:
关于java - 谁在 Spring MVC 中设置请求内容类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8657585/