SpringMVC:@RequestBody-将请求json串转化成java对象,@ResponseBody-将java对象转换成json串输出
第一种:请求key/value,输出json串【最常用】
- Ajax:
<script type="text/javascript">
function login() {
$.ajax({
type : 'post',
url : '${pageContext.request.contextPath}/user/login.mvc',
//请求数据是key/value,这里不需要指定contentType,默认就是key/value类型
data:'username=cyn&age=18',
cache : false,
sync : true,
success : function(msg) {
//返回并解析json串
alert(msg.username);
},
error : function() {
alert("请求失败!");
}
});
}
</script>
- SpringMVC:
@RequestMapping("login")
@ResponseBody
public User login(User user){
System.out.println(user);
return user;
}
第二种:请求json串,输出json串
- Ajax:
<script type="text/javascript">
function login() {
$.ajax({
type : 'post',
url : '${pageContext.request.contextPath}/user/login.mvc',
//指定请求数据格式是json串
contentType:'application/json;charset=utf-8',
data:'{"username":"zhangsan","age":"12"}',
cache : false,
sync : true,
success : function(msg) {
//从返回结果集中获取username的值
alert(msg.username);
},
error : function() {
alert("请求失败!");
}
});
}
</script>
- SpringMVC:
@RequestMapping("login")
@ResponseBody
public User login(@RequestBody User user){
System.out.println(user);
return user;
}
第三种: 请求key/value,输出字符串
- Ajax:
<script type="text/javascript">
function login() {
$.ajax({
type : 'post',
url : '${pageContext.request.contextPath}/user/login.mvc',
//请求数据是key/value,这里不需要指定contentType,默认就是key/value类型
data:'username=cyn&age=18',
cache : false,
sync : true,
success : function(msg) {
//返回并打印字符串
alert(msg);
},
error : function() {
alert("请求失败!");
}
});
}
</script>
- SpringMVC:
@RequestMapping("login")
public void login(HttpServletResponse response,User user){
System.out.println(user);
try {
response.getWriter().write(user.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}