一尘不染

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

java

我在注释驱动的Spring MVC Java Web应用程序中运行在Jetty Web服务器上运行(当前在Maven Jetty插件中)。

我正在尝试使用一种仅返回String帮助文本的控制器方法来提供一些AJAX支持。资源采用UTF-8编码,字符串也采用UTF-8编码,但是我来自服务器的回复是

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

即使我的浏览器发送

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

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

我发现了将这个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;
}

阅读 525

收藏
2020-03-11

共2个答案

一尘不染

简单声明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>

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

因此,也许最方便但最丑陋的方法是拦截AnnotationMethodHandlerAdapterwith的实例化BeanPostProcessor

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 " />
2020-03-11
一尘不染

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

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