springmvc 和 Ajax使用Json交互

前言

  • 前端到后台:前端ajax发送json格式字符串,后台直接接收为pojo参数,使⽤注解@RequstBody
  • 后台到前端:后台直接返回pojo对象,前端直接接收为json对象或者字符串,使⽤注解 @ResponseBody。当前流程不会走视图解析器,直接将数据写到输入流中。

使用步骤

  1. 创建springmvc工程,引入相关的依赖,配置web.xml和springmv.xml文件,创建对应的controller层,详细请查看springmvc的基础使用

  2. 导入json依赖的jar包

    <!--json数据交互所需jar,start-->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.9.0</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.9.0</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
      <version>2.9.0</version>
    </dependency>
    <!--json数据交互所需jar,end-->
    
  3. 导入jquery包,编写前端的示例代码

    在这里插入图片描述

    在springmvc.xml中加入jquery路径

    <!--静态资源配置,springmvc框架自己处理静态资源
        mapping:约定的静态资源的url规则
        location:指定静态资源的存放位置
    
    -->
    <mvc:resources mapping="/js/**" location="/WEB-INF/js/"/>
    

    jsp代码

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>Title</title>
    
        <script type="text/javascript" src="/js/jquery-3.6.0.min.js"></script>
    
        <script>
    
            $(function () {
    
                $("#ajaxBtn").bind("click", function () {
                    //发送ajax请求:
                    $.ajax({
                        url:'/demo/handleAjax',
                        type:'POST',
                        data:'{"name":"lisi", "birthday":"1991-02-01"}',
                        contentType:"application/json;charset=utf-8",
                        dataType:'json',
                        success:function (data) {
                            alert(data.name);
                        }
                    })
                });
            });
    
        </script>
    
    </head>
    <body>
    
        <div>
            <input type="button" value="Ajax提交" id="ajaxBtn">
        </div>
    
    </body>
    </html>
    
  4. 后台handler的测试代码

        //Ajax发送数据,前台传递json,后台直接转为Pojo对象
        @RequestMapping("/handleAjax")
        public @ResponseBody User handleAjax(@RequestBody User user){
    
            user.setName("王五");
            return user;
        }
    
  5. 测试

    在这里插入图片描述


总结

  • springmvc支持ajax使用json进行交互,主要使用@RequstBody 和 @ResponseBody两个注解标明即可。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值