@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;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.app = applicationContext;
}
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
try {
RequestMappingHandlerAdapter requestMappingHandlerAdapter = app.getBean(RequestMappingHandlerAdapter.class);
if(requestMappingHandlerAdapter!=null) {
List<HttpMessageConverter<?>> messageConverters = requestMappingHandlerAdapter.getMessageConverters();
if(messageConverters!=null) {
<bean id="mappingJackson2HttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>
设置返回json数据的编码为UTF-8。