SpringMVC返回字符串中⽂乱码
@ResponseBody
@RequestMapping(value = "/save")
public String callSomeone() {
return "保存成功";
}
显⽰乱码
设置了CharacterEncodingFilter为UTF-8,
⽅法⼀:
指定RequestMapping的produces属性
@RequestMapping(value = "/addOrder",produces = "text/html;charset=utf-8")
public String addOrder(){
Order order = new Order(100,"连⾐裙",8);
orderService.addOrder(order);
return "增加订单成功";
}
⽅法⼆:
SpringMVC返回字符串的编码与StringHttpMessageConverter的DefaultCharset属性有关
修改StringHttpMessageConverter的DefaultCharset属性
新建⼀个⼯具类 AppUtil实现ApplicationContextAware接⼝,并监听ContextRefreshedEvent事件
@Component
public class AppUtil implements ApplicationContextAware, ApplicationListener<ContextRefreshedEvent> {
private ApplicationContext app;
spring是什么意思啊中文@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.app = applicationContext;
}
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
try {
RequestMappingHandlerAdapter requestMappingHandlerAdapter = Bean(RequestMappingHandlerAdapter.class);
if(requestMappingHandlerAdapter!=null) {
List<HttpMessageConverter<?>> messageConverters = MessageConverters();
if(messageConverters!=null) {
// 获取bean容器中的StringHttpMessageConverter,并修改DefaultCharset属性
for(HttpMessageConverter item : messageConverters) {
if(item instanceof StringHttpMessageConverter) {
((StringHttpMessageConverter) item).setDefaultCharset(StandardCharsets.UTF_8);
}
}
}
}
}catch (BeansException e) {
}
}
}
<bean id="mappingJackson2HttpMessageConverter" class="org.verter.json.MappingJackson2HttpMessageConverter">        <property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>
设置返回json数据的编码为UTF-8。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。