引起乱码原因为spring mvc使用的默认处理字符串编码为ISO-8859-1,具体参考org.springframework.http.converter.StringHttpMessageConverter类中public static final Charset DEFAULT_CHARSET = Charset.forName("ISO-8859-1");
- 第一种方法:
对于需要返回字符串的方法添加注解,如下:
/***
* 返回类型是string需要用produces进行转码,并格式化
* json格式化 可以用Gson处理(obj <-> json)互相转换
* @return
* @date 2017年5月12日
* @author wanwenjun
*/
@RequestMapping(value="/stu",produces="application/json; charset=utf-8")
@ResponseBody
public String getStudent(){
Student s = (Student) SpringContext.getBean("student");
Gson gson = new Gson();
//obj to String
String stu = gson.toJson(s);
//String to obj
Student s2 = gson.fromJson(stu,Student.class);
System.out.println(s2.toString());
return stu;
}
使用modelandview,需Jackson支持,如下:
/****
* 效果和Map一致,但需要jackson jar包支持
* @date 2017年5月12日
* @author wanwenjun
* @return ModelAndView
*/
@ResponseBody
@RequestMapping(value="/student")
public ModelAndView getStu(String a){
Student s = (Student) SpringContext.getBean("student");
Map<String, Student> map = new HashMap<>();
map.put("stu", s);
return new ModelAndView(new MappingJackson2JsonView(),map);
}
上述方法只针对单个调用方法起作用。
两种方式有什么区别呢?
方式一:使用ModelAndView的contentType是"application/json"
方式二:返回String的 contentType是"text/html"
那么如何设置response的content type呢?
使用注解@RequestMapping 中的produces:
- 第二种方法
在配置文件中加入:
<mvc:annotation-driven> <mvc:message-converters register-defaults="true"> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <property name="supportedMediaTypes" value = "text/plain;charset=UTF-8" /> </bean> </mvc:message-converters> </mvc:annotation-driven>
参考:http://stackoverflow.com/questions/3616359/who-sets-response-content-type-in-spring-mvc-responsebody