前后端交互

ssm框架下,js页面通过json将数据发送到后台,后台处理之后,再将数据发送到前台。

在前台,要将用户名和邮箱发送到后台,先将用户名和和邮箱转成json形式的数据,在通过ajax发送到后台,其中url为后台要处理数据的地址。前台主要代码如下,其中User是一个实体类,有id,name,email,password等属性。

[html]  view plain  copy
  1. var user_json = {        
  2.                 "user_name": user_name,  
  3.                 "user_mail":user_mail  
  4.             }      
  5.   
  6.  //js对象转换成JSON字符串  
  7.             var jason_str = JSON.stringify(user_json);  
  8.   
  9.                 //Ajax发送数据给后台  
  10.                 $.ajax({  
  11.                     url :"/MyApplication/user/checkUserLogin",   
  12.                     cache : true,  
  13.                     type : "post",  
  14.                     datatype : "json",  
  15.                     contentType : "application/json; charset=utf-8",  
  16.                     data : jason_str,  
  17.                     success : function (data){  
  18.                         //返回空值  
  19.                         if(data==null){  
  20.                             alert("不存在该用户!");  
  21.                             window.location.href = "sighIn.html";  
  22.                         } else{  //存在该用户  
  23.                             if(password == data.user_password){  //密码正确  
  24.                                 window.location.href = "index.html?user_name=" + data.user_name;  
  25.                             }else{  //密码不正确  
  26.                                 alert("密码错误!");  
  27.                                 window.location.href = "sighIn.html";  
  28.                             }  
  29.                               
  30.                         }  
  31.                     }  
  32.                       
  33.                 });  

后台只要代码如下(在controller层编写)

[html]  view plain  copy
  1. @RequestMapping(value = "/checkUserLogin")  
  2.     public @ResponseBody User checkUserLogin(@RequestBody User user){  
  3.         if (user.getUser_name() != null) {  
  4.             user = userService.findByName(user.getUser_name());  
  5.         } else if (user.getUser_mail() != null) {  
  6.             user = userService.findByMail(user.getUser_mail());  
  7.         }  
  8.         return user;  
  9.     }  
@RequestBody是将json形式的数据转化成User类型的数据,@ResponseBody是将User类型的数据转成json发送到前端。

猜你喜欢

转载自blog.csdn.net/wang_666_/article/details/79472391