一、通過設置response編碼解決
response.setCharacterEncoding("utf-8");
二、設置requestMapping的product屬性解決
@RequestMapping(value = "/login.do",produces = "text/plain;charset=utf-8")
下面附上這裏的具體案例:
@RequestMapping(value = "/login.do",produces = "text/plain;charset=utf-8")
public String login(String username, String password, HttpServletRequest request, HttpServletResponse response){
response.setCharacterEncoding("utf-8");
List<User> users = userService.selectByUsername(username);
ImgFormat message = new ImgFormat();
// 通過用戶名來匹配登錄的用戶信息
for(User u : users){
if(u.getUsername().equals(username)){
if(u.getPassword().equals(password)){
// 將用戶信息保存到session中
HttpSession session = request.getSession();
session.setAttribute("user",u);
// 返回一個json格式的數據
message.setCode(1);
message.setMsg("登陸成功");
message.setData(JSONObject.fromObject(u));
return JSONObject.fromObject(message).toString();
}
message.setCode(0);
message.setMsg("密碼不正確");
return JSONObject.fromObject(message).toString();
}
message.setCode(0);
message.setMsg("賬號不存在");
return JSONObject.fromObject(message).toString();
}
message.setCode(0);
message.setMsg("請登錄賬戶");
return JSONObject.fromObject(message).toString();
}
參考文獻:Fantasy_99 SSM框架:解決後臺傳數據到前臺中文亂碼問題,使用@ResponseBody返回json 中文亂碼