SpringMVC返回字符串中⽂乱码
@ResponBody
@RequestMapping(value = "/save")
public String callSomeone() {
return "保存成功";
}
显⽰乱码
设置了CharacterEncodingFilter为UTF-8,
⽅法⼀:
指定RequestMapping的produces属性
moskau@RequestMapping(value = "/addOrder",produces = "text/html;chart=utf-8")
public String addOrder(){
Order order = new Order(100,"连⾐裙",8);
orderService.addOrder(order);
return "增加订单成功";
}
⽅法⼆:
SpringMVC返回字符串的编码与StringHttpMessageConverter的DefaultChart属性有关
修改StringHttpMessageConverter的DefaultChart属性
超速绯闻插曲
新建⼀个⼯具类 AppUtil实现ApplicationContextAware接⼝,并监听ContextRefreshedEvent事件
@Component
public class AppUtil implements ApplicationContextAware, ApplicationListener<ContextRefreshedEvent> {
2015六级private ApplicationContext app;
@Override
genitalpublic void tApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.app = applicationContext;
}
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
try {
RequestMappingHandlerAdapter requestMappingHandlerAdapter = Bean(RequestMappingHandlerAdapter.class);
if(requestMappingHandlerAdapter!=null) {
regalList<HttpMessageConverter<?>> messageConverters = MessageConverters();
magistaif(messageConverters!=null) {
protester
// 获取bean容器中的StringHttpMessageConverter,并修改DefaultChart属性
for(HttpMessageConverter item : messageConverters) {
if(item instanceof StringHttpMessageConverter) {如何梳头
((StringHttpMessageConverter) item).tDefaultChart(StandardCharts.UTF_8);
盘弄
}
}
}
}
}catch (BeansException e) {
paran
}
}
}
<bean id="mappingJackson2HttpMessageConverter" class="org.verter.json.MappingJackson2HttpMessageConverter"> <property name="supportedMediaTypes">
<list>
<value>text/html;chart=UTF-8</value>
</list>
</property>
</bean>
设置返回json数据的编码为UTF-8。