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

问题

我在我的Annotation驱动的Spring MVC Java Web应用程序中运行在jetty Web服务器上(目前在maven jetty插件中)。

我正在尝试使用一个控制器方法执行一些AJAX支持,只返回String帮助文本。资源采用UTF-8编码,字符串也是如此,但我的服务器响应来自于

content-encoding: text/plain;charset=ISO-8859-1

即使我的浏览器发送

Accept-Charset  windows-1250,utf-8;q=0.7,*;q=0.7

我正在以某种方式使用弹簧的默认配置

我发现了一个提示将这个bean添加到配置中,但我认为它只是没有使用,因为它说它不支持编码,而是使用默认编码。

<bean class="org.springframework.http.converter.StringHttpMessageConverter">
    <property name="supportedMediaTypes" value="text/plain;charset=UTF-8" />
</bean>

我的控制器代码是(请注意,此响应类型的更改对我不起作用):

@RequestMapping(value = "ajax/gethelp")
public @ResponseBody String handleGetHelp(Locale loc, String code, HttpServletResponse response) {
    log.debug("Getting help for code: " + code);
    response.setContentType("text/plain;charset=UTF-8");
    String help = messageSource.getMessage(code, null, loc);
    log.debug("Help is: " + help);
    return help;
}

#1 热门回答(144 赞)

我找到了Spring 3.1的解决方案。使用@ResponseBody注释。以下是使用Json输出的控制器示例:

@RequestMapping(value = "/getDealers", method = RequestMethod.GET, 
produces = "application/json; charset=utf-8")
@ResponseBody
public String sendMobileData() {

}

#2 热门回答(57 赞)

简单声明StringHttpMessageConverterbean是不够的,你需要将它注入AnnotationMethodHandlerAdapter

<bean class = "org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
        <array>
            <bean class = "org.springframework.http.converter.StringHttpMessageConverter">
                <property name="supportedMediaTypes" value = "text/plain;charset=UTF-8" />
            </bean>
        </array>
    </property>
</bean>

但是,使用此方法你必须重新定义所有HttpMessageConverter,并且它不适用于<mvc:annotation-driven />

所以,也许最方便但最丑陋的方法是拦截AnnotationMethodHandlerAdapterwithBeanPostProcessor的实例化:

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;
    }

    public Object postProcessAfterInitialization(Object bean, String name)
            throws BeansException {
        return bean;
    }
}
<bean class = "EncodingPostProcessor " />

#3 热门回答(48 赞)

请注意,在Spring MVC 3.1中,你可以使用MVC命名空间来配置消息转换器:

<mvc:annotation-driven>
  <mvc:message-converters register-defaults="true">
    <bean class="org.springframework.http.converter.StringHttpMessageConverter">
      <property name="supportedMediaTypes" value = "text/plain;charset=UTF-8" />
    </bean>
  </mvc:message-converters>
</mvc:annotation-driven>

或基于代码的配置:

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

  private static final Charset UTF8 = Charset.forName("UTF-8");

  @Override
  public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    StringHttpMessageConverter stringConverter = new StringHttpMessageConverter();
    stringConverter.setSupportedMediaTypes(Arrays.asList(new MediaType("text", "plain", UTF8)));
    converters.add(stringConverter);

    // Add other converters ...
  }
}