springmvc ajax返回数据中文乱码 问题经常出现,这里提供两种解决办法。
这里是一个 登录的例子,ajax 验证用户名和密码$("#loginForm").submit(function () {
$.ajax({
async: true,
type: "POST",
url: '${pageContext.request.contextPath}/loginVerify',
contentType: "application/x-www-form-urlencoded; charset=utf-8",
data: $("#loginForm").serialize(),
dataType: "json",
success: function (data) {
if(data.code==0) {
alert(data.msg);
} else {
window.location.href="${pageContext.request.contextPath}/admin";
}
},
error: function () {
alert("数据获取失败")
}
})
})
方法一、配置springMVC编码过滤器
这种方法较为常见,在 web.xml顶部添加如下代码CharacterEncodingFilter
org.springframework.web.filter.CharacterEncodingFilter
encoding
UTF-8
forceEncoding
true
CharacterEncodingFilter
/*
注意:最好把这段代码放在web.xml中开头的位置,因为拦截有顺序,如果放在后面的话容易拦截不到。
方法二、@RequestMapping里面加入produces = “text/plain;charset=UTF-8”
@RequestMapping(value = "/loginVerify",method = RequestMethod.POST,produces = "text/plain;charset=UTF-8")
@ResponseBody
public String loginVerify(HttpServletRequest request) throws Exception {
Mapmap = new HashMap();
String user = request.getParameter("user");
String password = request.getParameter("password");
UserCustom userCustom = userService.getUserByNameOrEmail(user);
String message="";
if(userCustom==null) {
map.put("code",0);
map.put("msg","用户名无效!");
} else if(!userCustom.getUserPass().equals(password)) {
map.put("code",0);
map.put("msg","密码错误!");
} else {
map.put("code",1);
map.put("msg","");
request.getSession().setAttribute("userId", userCustom.getUserId());
}
String result = new JSONObject(map).toString();
return result;
}