springmvc注解RequestBody和ResponseBody
程序员文章站
2022-07-12 19:18:23
...
@responseBody将后台pojo转换json对象,返回到页面。
@RequestBody接受前台json数据,将json数据自动封装javaBean。
需要导入对json数据转换所依赖的jar,否则会找不到请求的方法
1.页面传递json格式数据
后台方法
@RequestMapping("requestJson")
public @ResponseBody User requestJson(@RequestBody User user){
System.out.println(user);
return user;
}
页面传递参数
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>ajax请求</title>
<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-2.0.3.min.js"></script>
</head>
<body>
<input type="button" value="请求json数据" onclick="requestJson();"/>
</body>
<script type="text/javascript">
function requestJson(){
var pojoJson = JSON.stringify({"id":"12","userName":"张三","age":"18"});
var url = "${pageContext.request.contextPath }/user/requestJson.do";
$.ajax({
url:url,
type:"post",
contentType:"application/json;charset=utf-8",
data:pojoJson,
success:function(data){
alert(data);
}
});
}
</script>
</html>
请求过程
2.页面传递普通格式数据
后台
@RequestMapping("requestPojo")
public @ResponseBody User requestPojo(User user){
System.out.println(user);
return user;
}
页面
<body>
<input type="button" value="普通数据提交" onclick="requestPojo();"/>
</body>
<script type="text/javascript">
function requestPojo(){
var pojoJson = JSON.stringify({"id":"12","userName":"张三","age":"18"});
var url = "${pageContext.request.contextPath }/user/requestPojo.do";
$.ajax({
url:url,
type:"post",
data:"id=16&userName=李四&age=19",
success:function(data){
alert(data);
}
});
}
</script>
推荐阅读
-
springmvc注解@Controller和@RequestMapping
-
SpringMVC注解之@ResponseBody注解原理
-
SpringMVC配置式开发、注解式开发和控制器参数说明
-
@RequestBody和@ResponseBody的使用情形以及RestTemplate的http报文转换
-
spring和springmvc的注解总结
-
SpringMVC 中@RequestParam注解、@RequestHeader注解、@RequestBody注解请求
-
Spring @RequestBody与@ResponseBody注解
-
springmvc注解RequestBody和ResponseBody
-
@ResponseBody和@RequestBody区别
-
SpringMVC的RequestBody注解