ssm框架下,js页面通过json将数据发送到后台,后台处理之后,再将数据发送到前台。
在前台,要将用户名和邮箱发送到后台,先将用户名和和邮箱转成json形式的数据,在通过ajax发送到后台,其中url为后台要处理数据的地址。前台主要代码如下,其中User是一个实体类,有id,name,email,password等属性。
var user_json = {
"user_name": user_name,
"user_mail":user_mail
}
//js对象转换成JSON字符串
var jason_str = JSON.stringify(user_json);
//Ajax发送数据给后台
$.ajax({
url :"/MyApplication/user/checkUserLogin",
cache : true,
type : "post",
datatype : "json",
contentType : "application/json; charset=utf-8",
data : jason_str,
success : function (data){
//返回空值
if(data==null){
alert("不存在该用户!");
window.location.href = "sighIn.html";
} else{ //存在该用户
if(password == data.user_password){ //密码正确
window.location.href = "index.html?user_name=" + data.user_name;
}else{ //密码不正确
alert("密码错误!");
window.location.href = "sighIn.html";
}
}
}
});
后台只要代码如下(在controller层编写)
@RequestMapping(value = "/checkUserLogin")
public @ResponseBody User checkUserLogin(@RequestBody User user){
if (user.getUser_name() != null) {
user = userService.findByName(user.getUser_name());
} else if (user.getUser_mail() != null) {
user = userService.findByMail(user.getUser_mail());
}
return user;
}
@RequestBody是将json形式的数据转化成User类型的数据,@ResponseBody是将User类型的数据转成json发送到前端。
代码链接 https://pan.baidu.com/s/1zeC2xDKmhZyP1WElUjRA7w 提取码 m7z4
有需要自己下载查看