SpringMVC处理ajax请求(@RequestBody注解),ajax向后端传递的数据格式详解

目录

@RequestBody注解简单介绍

@RequestBody获取json格式的请求参数

Servlet方式处理ajax请求


本文讲解两种方式实现SpringMVC与Ajax交互,1、通过SpringMVC提供的注解@RequestBody处理ajax请求;2、通过JavaEE时期的Servlet来处理

@RequestBody注解简单介绍

@RequestBody可以获取请求体信息,使用@RequestBody注解标识控制器方法的形参,当前请求的请求体就会为当前注解所标识的形参赋值

复制代码
<!--此时必须使用post请求方式,因为get请求没有请求体-->
<form th:action="@{/test/RequestBody}" method="post">
  用户名:<input type="text" name="username"><br>
  密码:<input type="password" name="password"><br>
  <input type="submit">
</form>

@RequestMapping("/test/RequestBody")
public String testRequestBody(@RequestBody String requestBody){ 
    System.out.println("requestBody:"+requestBody);
    return "success";
}

输出结果就是在页面填写的值。

@RequestBody获取json格式的请求参数

在使用ajax时发送的数据必须是json字符串

创建一个user实体类对象

复制代码
//将json格式的数据转换为实体类对象
@RequestMapping("/test/RequestBody/json")
public void testRequestBody(@RequestBody User user, HttpServletResponse response) throws IOException, IOException {
    System.out.println(user);
//User{id=null, username='admin', password='123456', age=null, gender='null'}
    response.getWriter().print("hello,axios");
}

前端ajax格式:

复制代码
$.ajax({
  url: 'test/RequestBody/json',
  type: 'POST',
  contentType: 'application/json', // 设置内容类型
  //必须是json字符串
  data: '{"username": "admin", "password":"123456"}' ,//JSON.stringify(data), // 将数据转换为JSON字符串
  dataType: 'text', // 指定预期的服务器响应数据类型也为JSON
  success: function(response) {
    alert(response);
  },
  error: function(xhr, status, error) {
    console.error('Error:', error);
  }
});

Servlet方式处理ajax请求

不用加上@RequestBody注解

复制代码
@RequestMapping("/test/RequestOOBody/json")
public void testRequestBody(User user, HttpServletResponse response) throws IOException, IOException {
    System.out.println(user);
    //User{id=null, username='admin', password='123456', age=null, gender='null'}
    response.getWriter().print("hello,axios");
}

前端

复制代码
$.ajax({
  url: 'test/RequestOOBody/json',
  type: 'POST',
  contentType: 'application/x-www-form-urlencoded', // 设置内容类型
  data: "username=shang&password=123456" ,
  dataType: 'text', // 指定预期的服务器响应数据类型也为JSON
  success: function(response) {
    alert(response);
  },
  error: function(xhr, status, error) {
    console.error('Error:', error);
  }
});

这两种方式的区别在前端ajax请求时数据的类型要求,使用SpringMVC注解方式就必须传json字符串形式的数据。传统JavaEE方式就是&连接的字符串,contentType也要随之改变。

相关推荐
yuniko-n5 分钟前
【JUC】Thread 内存泄露
java
freejackman5 分钟前
【架构篇】双遍历 + 多栈协同:手撸 SQL 血缘引擎的架构思考
java·大数据·数据库·hive·sql·架构·spark
企业数字化笔记12 分钟前
业务单据怎样接入流程中心?启动条件、实例关联与失败回退
java·spring boot·mysql
挖掘狂人20 分钟前
同一个端口能不能被两个程序同时监听?
java·后端·程序员
codigger24 分钟前
同一个端口能不能被两个程序同时监听?
java·后端·程序员·编程
西索斯coding24 分钟前
qwen3.8-max-0902 和 minimax-m3 改真实仓库差多少?2026 年 50 个缺陷复现实测框架
java·服务器·网络·ai
2501_9339232532 分钟前
SpringCloud:OpenFeign快速实现
java·后端·spring cloud·openfeign
denlaku40 分钟前
JDK 26 新特性详解
java
SL_staff44 分钟前
3分钟完成业务规则调整:告别代码修改,实现拖拽式逻辑配置
java·低代码·全栈
Flynn Liang1 小时前
让 AI 查订单、查库存、发消息:Spring AI 自定义工具(Tool)实战与工具描述工程
java·人工智能·spring·函数调用·springai·tool·自定义工具