java Spring MVC 响应编码问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6638284/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 16:44:53  来源:igfitidea点击:

Spring MVC response encoding issue

javaservletsspring-mvccharacter-encoding

提问by ant

In last few hours I've read a lot concerning this topic, and so far nothing has worked. I'm trying to return response containing "odd" some characters. Here is example of that, quite simple :

在过去的几个小时里,我阅读了很多关于这个主题的文章,但到目前为止没有任何效果。我正在尝试返回包含“奇数”某些字符的响应。这是一个例子,很简单:

@ResponseBody
    @RequestMapping(value="test")
    public String test(){
        String test = "?????";
        System.out.println(test);
        logger.info(test);
        return test;
    }

This is my web.xml, because I found some answers where CharacterEncodingFilter helped(not in my case though). I used POST method because I read this applies to POST.

这是我的web.xml,因为我在 CharacterEncodingFilter 帮助下找到了一些答案(虽然不是我的情况)。我使用 POST 方法是因为我读到这适用于 POST。

Also found this answer(related). Didn't help as well.

还找到了这个答案(相关)。也没有帮助。

When I debug it the correct value appears, but when I print it doesn't as it can be seen below:

当我调试它时,会出现正确的值,但是当我打印它时却没有,如下所示:

enter image description here

在此处输入图片说明

When I test it from jmeter, the response seems to be OK, Content-Typeis text/html;charset=UTF-8

当我从 jmeter 测试它时,响应似乎没问题,Content-Typetext/html;charset=UTF-8

Here is a screenshot of that as well. http://i56.tinypic.com/14lt653.jpg

这也是一个截图。http://i56.tinypic.com/14lt653.jpg

I think the right way is to return UTF-8, maybe I'm wrong.

我认为正确的方法是返回UTF-8,也许我错了。

采纳答案by ant

After few days of this I just had "who's your daddy moment". It came from reading spring 3.0 reference, I had nothing else to try so why not go trough entire documentation.. and combination of @axtavt answer :

几天后,我刚刚有了“谁是你爸爸的时刻”。它来自阅读 spring 3.0 参考,我没有其他可尝试的,所以为什么不通过整个文档......和@axtavt 的组合回答:

Who sets response content-type in Spring MVC (@ResponseBody)

谁在 Spring MVC 中设置响应内容类型(@ResponseBody)

Changed original solution :

更改原始解决方案:

public class EncodingPostProcessor implements BeanPostProcessor {
    public Object postProcessBeforeInitialization(Object bean, String name)
            throws BeansException {
        if (bean instanceof AnnotationMethodHandlerAdapter) {
            HttpMessageConverter<?>[] convs = ((AnnotationMethodHandlerAdapter) bean).getMessageConverters();
            for (HttpMessageConverter<?> conv: convs) {
                if (conv instanceof StringHttpMessageConverter) {
                    ((StringHttpMessageConverter) conv).setSupportedMediaTypes(
                        Arrays.asList(new MediaType("text", "html", 
                            Charset.forName("UTF-8"))));
                }
            }
        }
        return bean;
    }

To :

到 :

public class EncodingPostProcessor implements BeanPostProcessor {
    public Object postProcessBeforeInitialization(Object bean, String name)
            throws BeansException {
        if (bean instanceof AnnotationMethodHandlerAdapter) {
            HttpMessageConverter<?>[] convs = ((AnnotationMethodHandlerAdapter) bean).getMessageConverters();
            for (HttpMessageConverter<?> conv: convs) {
                if (conv instanceof StringHttpMessageConverter) {
                    ((StringHttpMessageConverter) conv).setSupportedMediaTypes(
                        Arrays.asList(new MediaType("text", "plain", 
                            Charset.forName("UTF-8"))));
                }
            }
        }
        return bean;
    }

Darn spring!!! but still I'll continue to use it.

该死的春天!!!但我还是会继续使用它。

回答by Trung

My simple solution:

我的简单解决方案:

@RequestMapping(value="test")
public ModelAndView test(){
  String test = "?????";
  ...
  ModelAndView mav = new ModelAndView("html_utf8");
  mav.addObject("responseBody", test);
}

and the view html_utf8.jsp

和视图 html_utf8.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>${responseBody}

No additional classes and configuration.
And You can also create another view (for example json_utf8) for other content type.

没有额外的类和配置。
并且您还可以为其他内容类型创建另一个视图(例如 json_utf8)。

回答by Micha?

Instead @ResponseBody use ResponseEntity.

相反,@ResponseBody 使用 ResponseEntity。

@RequestMapping(value="test")
public ResponseEntity<String> test(){
    String test = "?????";
    System.out.println(test);
    logger.info(test);
    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.add("Content-Type", "application/json; charset=UTF-8");
    return ResponseEntity<String>(test,responseHeaders, HttpStatus.OK);
}

回答by Stephen C

I can see two problems in the actual delivered response.

我可以在实际交付的响应中看到两个问题。

  • The response is clearly just text, but your response content-type header is saying it is HTML.

  • Judging from the content-length of the response, the content has not actually been encoded in UTF-8.

  • 响应显然只是文本,但您的响应内容类型标头表明它是 HTML。

  • 从响应的 content-length 来看,内容实际上并没有被编码为 UTF-8。



FWIW - the CharacterEncodingFilterwon't help with your problem because it is dealing with the encoding of the request not the response.

FWIW - 这CharacterEncodingFilter对您的问题没有帮助,因为它处理的是请求的编码而不是响应。



I think that the problem is that you need to configure the message converter for the response body. However, it appears that your application already does something in this area, because the default behavior of the StringHttpMessageConverter is to use "text/plain" as its content type.

我认为问题在于您需要为响应正文配置消息转换器。但是,您的应用程序似乎已经在这方面做了一些事情,因为 StringHttpMessageConverter 的默认行为是使用“text/plain”作为其内容类型。