Ajax和SpringMVC之间的json数据传输有两种方式:
1.直接传输Json对象
2.将Json序列化成json字符串
1.直接传输Json对象
前端Ajax
$(document).ready(function(){
$("#btn_login").click(function(){
var dataJson = {
username:$("#username").val(),
password:$("#password").val()
};
$.ajax({
url:"/login/",
type:"post",
data:dataJson,
contentType:"application/x-www-form-urlencoded",//如不设置此项,默认也为此,设置发送给后端的类型
dataType:"json",//设置接收后端的数据的类型
async:true,//设置异步,不然可能接收不到后端返回的json
success:function(data){//data为后端返回的json
if(data.code==0){
window.location.reload();
}
else {
}
}
});
});
});
后端使用
@RequestMapping(path = {"/login/"}, method = {RequestMethod.GET, RequestMethod.POST})
@ResponseBody
public String login(@RequestParam("username") String username,
@RequestParam("password") String password,
HttpServletResponse response) {
try {
Map<String, Object> map = userService.login(username, password);
if (map.containsKey("ticket")) {
Cookie cookie = new Cookie("ticket", map.get("ticket").toString());
cookie.setPath("/");
response.addCookie(cookie);
//return "redirect:/";
return CommonUtil.getJSONString(0, "成功");
} else {
//return "redirect:/";
return CommonUtil.getJSONString(1, map);
}
} catch (Exception e) {
logger.error("登录异常" + e.getMessage());
//return "redirect:/";
return CommonUtil.getJSONString(1, "注册异常");
}
}
使用@RequestParam,即使用Servlet的request.getgetParameter。这种方式可以接受以application/x-www-form-urlencoded这种方式传输的JSON对象的。
2.将Json序列化
前端Ajax
$(document).ready(function(){
$("#btn_reg").click(function(){
var dataJson = {
username:$("#regusername").val(),
password:$("#regpassword").val()
};
$.ajax({
url:"/reg/",
type:"post",
contentType:"application/json",//以json字符串形式传输
data:JSON.stringify(dataJson),//将json对象序列化成字符串
dataType:"json",
async:true,
success:function(data){
if(data.code==0){
window.location.reload();
}
else {
}
}
});
});
});
后端Controller
@RequestMapping(path = {"/reg/"}, method = {RequestMethod.GET, RequestMethod.POST})
@ResponseBody
public String reg(@RequestBody User user,
HttpServletResponse response) {
try {
Map<String, Object> map = userService.register(user.getUsername(), user.getPassword());
if (map.containsKey("ticket")) {
Cookie cookie = new Cookie("ticket", map.get("ticket").toString());
cookie.setPath("/");
response.addCookie(cookie);
return CommonUtil.getJSONString(0, "注册成功");
} else {
return CommonUtil.getJSONString(1, map);
}
} catch (Exception e) {
logger.error("注册异常" + e.getMessage());
return CommonUtil.getJSONString(1, "注册异常");
}
}
@RequestBody中的user中,必须有与前端名称一致的属性,才可以接受到相应数据。
除此之外,@RequestBody还可用Map<String,Object> map来接收。