谁在S​​pring MVC中设置了请求内容类型

时间:2011-12-28 15:12:01

标签: java json web-applications spring-mvc encoding

我已阅读帖子“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字符。

这里可能出现什么问题?请给我一些提示,谢谢。 乔治

1 个答案:

答案 0 :(得分:4)

我遇到了类似的问题JSON&amp; Spring并通过在我的Tomcat server.xml配置中的URIEncoding="UTF-8"上指定<Connector>解决了该问题,如下所述:

http://wiki.apache.org/tomcat/FAQ/CharacterEncoding#Q8