SpringBoot获取前台传递对象的方法

SpringBoot获取前台传递对象的方法

首先说一下@RequestParam和@RequestBoby的区别:

  • @RequestParam:请求头参数,常用于get请求。content-type默认为application/x-www-form-urlencoded。即k-v键值对形式
    • 所以在postman或apifox中,如果是post请求。需要在boby中选择x-www-form-urlencoded,不能使用json
    • 在前台传递中,可以将content-type改为application/json,然后参数改为JSON.stringify(data),才能正确传递
  • @RequestBoby:请求体。一般用于处理content-type为application/json类型
  • 如果不加注解,则默认application/x-www-form-urlencoded。即k-v键值对形式

SpringBoot获取前台传递对象并不容易,稍有错误就会报错。这里提供一个大致模板方法:

前台代码:

let student = {
  id: 1,
  name: 'tom',
  email: '123@qq.com',
  age: 15
};

$('#pojoTest').click(function () {
  $.ajax({
    url: getContextPath() + `/test/test3`,
    type: "post",
    data: JSON.stringify(student),
    contentType: "application/json;charset=utf-8",
    success: function (result) {
        console.log(result);
    },
  });
});

后台代码:

@PostMapping("/test3")
public AjaxResult test3(@RequestBody Student student) {
  System.out.println(student);
  return AjaxResult.ok("姓名:" + student.getName());
}
  • 这里采用的方式就是post请求,前端更改contentType,data改为json,后台添加@RequestBoby注解
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值