代码如下:
Map<String,Object> map = new HashMap<>();
if("admin".equals(username) && "123".equals(password)) {
map.put("success",true);
map.put("message","登录成功");
req.getSession().setAttribute("username",username);
}else {
map.put("success",false);
map.put("message","登录失败");
}
resp.getWriter().write(JSON.toJSONString(map));
function login() {
$.ajax({
type: 'POST',
url: '/chat/login',
dataType: 'json',
data: {
username: $("#username").val(),
password: $("#password").val()
},
success: function (data) {
if (data.success) {
window.location.href = "index.jsp";
} else {
alert(data.message);
}
}
});
}
将Map转换成JSON格式时,需要设置ContentType
resp.setContentType("text/html;charset=utf-8");