前端传递对象参数,以及后端接受参数 @PathVariable @RequestParam @RequestBody 注解的使用

太久没写前后端传递参数了,总是格式对不上号


提示:以下是本篇文章正文内容,下面案例可供参考

一、接收参数注解 @PathVariable

拼接在 url 地址中的

请求 url 如 : http://localhost:8001/eduservice/edu-teacher/1/3 
这里的 1/3  这两个都是传递的参数

后端

@PostMapping("{page}/{limit}")
    @ApiOperation("条件分页查询讲师")
    public R pageWithConditions(@ApiParam(name = "page", value = "页码", required = true)
                                @PathVariable Integer page,
                                @ApiParam(name = "limit", value = "记录条数", required = true)
                                @PathVariable Integer limit) {}

前端
api

export function list(page, limit, searchObj) {
  return request({
    url: `/eduservice/edu-teacher/${page}/${limit}`,  // 这里的 page / limit 就是拼接到 url 当中的参数
    method: 'post'
  })
}

调用请求

      eduTeacherAPI
        .list(this.pageObj.pageNo, this.pageObj.pageSize)
        .then(res => {})

二、接收参数注解 @RequestParam

2.1 get 请求,普通类型参数

拼接在 url 地址后面的

请求 url 如 : http://localhost:8001/eduservice/edu-teacher/test?name=testName
这里的 name=testName 是传递的参数

后端

    @GetMapping("/test")
    public R TestParam(@ApiParam(name = "id", value = "查询讲师id", required = true) @RequestParam String name) {
        System.out.println(name);
        return R.ok();
    }

前端
api

export function testParam(name) {
  return request({
    url: '/eduservice/edu-teacher/test?name=' + name,
    method: 'get'
  })
}

调用请求

      const b = 'testName'
      eduTeacherAPI.testParam(b).then(res => {
        console.log(res)
      })

2.2 post 请求,普通类型参数

放在请求头当中

请求 url 如 :http://localhost:8001/eduservice/edu-teacher/test2?name=testName
这里的 name=testName 是传递的参数

后端

    @PostMapping("/test2")
    public R TestParam2(@ApiParam(name = "id", value = "查询讲师id", required = true) @RequestParam String name) {
        System.out.println(name);
        return R.ok();
    }

前端
api

export function testParam2(name) {
  return request({
    url: '/eduservice/edu-teacher/test2',
    method: 'post',
    params: {  // 这里需要是 params  如果写 data 会报错
      name
    }
  })
}

调用请求

      const b = 'testName'
      eduTeacherAPI.testParam2(b).then(res => {
        console.log(res)
      })

三、接收参数注解 @RequestBody

post 请求,对象类型参数

前端传递对象,后端接收对象
放在请求体中的 payload / 负载
在这里插入图片描述

后端

    @PostMapping()
    @ApiOperation("条件分页查询讲师")
    public R pageWithConditions(@ApiParam(name = "queryTeacher", value = "查询对象", required = false)
                                @RequestBody QueryTeacher queryTeacher) {}

前端
api

export function list(page, limit, searchObj) {
  return request({
    url: `/eduservice/edu-teacher`,  // 这里的 page / limit 就是拼接到 url 当中的参数
    method: 'post',
    // data: { queryTeacher: searchObj }  注意这样子写是错误的
    data: searchObj
  })
}

调用请求

      eduTeacherAPI
        .list(this.pageObj.searchObj)
        .then(res => {})

总结

例如:以上就是今天要讲的内容,本文仅仅简单介绍了 前端传递普通类型参数和对象时前端传递的方式以及后端接受是注解的使用

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>