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

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

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

简单声明

StringHttpMessageConverter
bean是不够的,您需要将其注入
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 />

因此,也许最方便但最丑陋的方法是拦截

AnnotationMethodHandlerAdapter
with的实例化
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 " />


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/4900872.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-12
下一篇 2022-11-12

发表评论

登录后才能评论

评论列表(0条)

保存