重要的是定位问题的方法和解决问题的耐心!
场景一:SpringMVC+JSON+@ResponseBody
先上截图:
接下来,我们看一下Controller里面的代码:
@RequestMapping(value="/add", method=RequestMethod.POST)
public @ResponseBody String add(String categoryName, String categoryRemark){
GoodsCategory record=new GoodsCategory();
record.setName(categoryName);
record.setRemark(null);
record.setCreateDate(new Date());
record.setState("U");//使用
Object obj=categoryMapper.selectByName(categoryName);
String msg=null;
if(obj!=null){
msg= "信息已经存在";
}else{
int result = categoryMapper.insertSelective(record);
msg="保存成功";
}
return msg;
}
我们这里是使用@ResponseBody将返回值转换成JSON格式输出到页面。
配置文件是:
<bean id="mappingJacksonHttpMessageConverter"
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/json</value>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>
<!-- 启动SpringMVC的注解功能,完成请求和注解POJO的映射 -->
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="mappingJacksonHttpMessageConverter" /> <!-- JSON转换器 -->
</list>
</property>
</bean>
然后我们抓包看一下请求,我用的是chrome的F12功能:
我们看到标红的位置是响应部分,这里使用默认的字符集,原来是我们没有指定字符集导致的乱码,那么我们在响应的时候要手动指定字符集
使用@ResponseBody的produces属性,代码:
@RequestMapping(value="/add", method=RequestMethod.POST, produces="text/html;charset=UTF-8")
然后我们重启服务器再看看结果
已经解决,抓包看一下有什么变化:
可以看出来响应的字符集已经被设置。
但是,这是处理一个有中文的请求,如果我们的请求好多都包含中文,那么岂不是都要写这句话?多累的!
别担心,有解决办法,这里其实和org.springframework.http.converter.StringHttpMessageConverter有关系我们查看源码:
看它的默认构造函数:
public StringHttpMessageConverter() {
this(DEFAULT_CHARSET);
}
那么这个DEFAULT_CHARSET是个什么玩意呢?
他是这样定义的
这是个西欧编码,不支持中文,因此我们需要使用他父类的方法,传入编码来改变它的默认方式
public static final Charset DEFAULT_CHARSET = Charset.forName("ISO-8859-1");
这是个西欧编码,不支持中文,因此我们需要使用他父类的方法,传入编码来改变它的默认方式
org.springframework.http.converter.AbstractHttpMessageConverter.setSupportedMediaTypes(List<MediaType>)
<span style="white-space:pre"> </span>/**
* Set the list of {@link MediaType} objects supported by this converter.
*/
public void setSupportedMediaTypes(List<MediaType> supportedMediaTypes) {
Assert.notEmpty(supportedMediaTypes, "'supportedMediaTypes' must not be empty");
this.supportedMediaTypes = new ArrayList<MediaType>(supportedMediaTypes);
}
然后我们更改我们的配置文件
<mvc:annotation-driven >
<mvc:message-converters register-defaults="true">
<!-- 解决@ResponseBody中文乱码 -->
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes" value = "text/plain;charset=UTF-8" />
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
在你的配置文件中可能是<mvc:annotation-driven />这样写的。
好了,试试吧。