二 @ResponseBody用法
@ResponseBody底层是通过response.getwriter()方法将数据写回前
台
@ResponseBody
@RequestMapping
(value="/queryList",method=RequestMethod.POST,produces =
"application/json; charset=utf-8")//防止乱码
public String queryList(HttpServletResponse
response)throws IOException{
response.setCharacterEncoding("utf-8");
List list = userService.queryList();
User user = (User)list.get(0);
//user.getCreateTime();
Integer userId = user.getUserId();
return "查询成功";
}
//===================================================
防止中文乱码
引起乱码原因为spring mvc使用的默认处理字符串编码为ISO-8859-1
,具体参考
org.springframework.http.converter.StringHttpMessageConver
ter类中public static final Charset DEFAULT_CHARSET =
Charset.forName("ISO-8859-1");
解决方法:
第一种方法:
对于需要返回字符串的方法添加注解,如下:
@RequestMapping(value="/getUsers", produces =
"application/json; charset=utf-8")
public String getAllUser() throws
JsonGenerationException, JsonMappingException, IOException
{
List<User> users = userService.getAll();
ObjectMapper om = new ObjectMapper();
System.out.println(om.writeValueAsString(users));
DataGrid dg = new DataGrid();
dg.setData(users);
return om.writeValueAsString(dg);
}
此方法只针对单个调用方法起作用。
第二种方法:
在配置文件中加入
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean
class="org.springframework.http.converter.StringHttpMessag
eConverter">
<property name="supportedMediaTypes" value =
"text/plain;charset=UTF-8" />
</bean>
</mvc:message-converters>
</mvc:annotation-driven>