欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

springmvc注解RequestBody和ResponseBody

程序员文章站 2022-07-12 19:18:23
...

@responseBody将后台pojo转换json对象,返回到页面。
@RequestBody接受前台json数据,将json数据自动封装javaBean。

需要导入对json数据转换所依赖的jar,否则会找不到请求的方法
springmvc注解RequestBody和ResponseBody

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>

请求过程
springmvc注解RequestBody和ResponseBody
springmvc注解RequestBody和ResponseBody
springmvc注解RequestBody和ResponseBody

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>
相关标签: spring mvc