SpringMVC与Jason联用自动封装

本文详细介绍了如何在SpringMVC项目中实现Ajax请求处理,包括导入必要坐标、使用jQuery发起Ajax请求、SpringMVC控制器逻辑处理及实体类响应。通过具体示例,展示从配置到功能实现的全过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.导入坐标

 <properties>
     ```
    <spring.version>5.0.2.RELEASE</spring.version>
    
  </properties>
  
 <dependencies>
    <dependency>
      <!--jason包-->
      <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-core</artifactId>
      <version>2.9.0</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
      <version>2.9.0</version>
    </dependency>
    <!--jason包-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>
  </dependencies>

2.在一个按钮上或者form表单上提交ajax请求

需要jQuery

        $(function () {
           $("#btnAjax").click(function () {
               $.ajax({
                   url: "view/testAjaxAndJason",
                   data: JSON.stringify({
                       "name": "zs",
                       "age": 18
                   }),
                   type: "post",
                   dataType: 'json',
                   contentType: 'application/json',
                   success: function (res) {
                            console.log(res);
                   }
               })
               });

        });

3.SpringMVC中逻辑处理

    /**
     * ajax请求必须是post请求,使用Jason包,自动把数据打入实体类
     * @param user
     */
    @RequestMapping("/testAjaxAndJason")
    public @ResponseBody User testAjaxAndJason(@RequestBody User user){
        System.out.println(user);
        /*返回值写入直接@ResponseBody,让MVC自动把user对象返回成json数据*/
        return user;
    }

4.其中Javabean

在这里插入图片描述

5.效果

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

这次最后一次熬夜

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值