问题:
后台代码如下:
@RequestMapping("menuTreeAjax")
@ResponseBody/*** 根据parentMenuId获取菜单的树结构
*@paramparentMenuId
*@return
*/
publicString menuTreeAjax(Integer parentMenuId) {
JSONArray array=menuService.getTreeMenuByParentMenuId(parentMenuId);returnarray.toString();
}
前台代码如下:
$.ajax({
url:'menuTreeAjax?parentMenuId=${menu.menuId}',
async:false,
dataType:"json",
success:function(data){
menuTree=data;
alert(data[0].text);
}
});
发现前台显示的json数据中的中文为???。乱码问题。
原因:
Spring中解析字符串的转换器默认编码居然是ISO-8859-1
如下所示:
解决方法:
方法一,使用(produces = "application/json; charset=utf-8")
@RequestMapping(value="menuTreeAjax", produces = "application/json; charset=utf-8")
@ResponseBody/*** 根据parentMenuId获取菜单的树结构
*@paramparentMenuId
*@return
*/
publicString menuTreeAjax(Integer parentMenuId) {
JSONArray array=menuService.getTreeMenuByParentMenuId(parentMenuId);returnarray.toString();
}
方法二:在springmvc.xml配置:
application/json;charset=UTF-8
PS:如果返回的不是json,而只是一个字符串,则只需要这样就可以了。将produces改为text/html
@ResponseBody
@RequestMapping(value="webserviceDemo1", produces = "text/html; charset=utf-8")publicString webserviceDemo1(){
WeatherServiceService factory=newWeatherServiceService();
WeatherService service=factory.getWeatherServicePort();
String result=service.getWeatherByCityname("厦门");returnresult;
}