乐趣区

关于java:SpringBoot参数请求方式

咱们心愿咱们的参数可能依照咱们构想的、失常的发送到后端接口,然而 post、get 和各种接参的 api 容易让人迷糊,上面我说下本人的了解。

1、前端传参形式

传参能够将参数放到 header 外面,也能够拼到地址中,或者放在 body 中,不过个别 header 中只放一些校验的参数。

1.1 get 申请

get 申请个别只容许在 url 尾部拼接参数,如 http://localhost:9003/mid/app/queryTagByMenu?name=1

get 申请也能够将参数放到门路中,如 http://localhost:9003/mid/app/queryTagByMenu/1

1.2 post 申请

get 申请能够将参数放到门路中,如 http://localhost:9003/mid/app/queryTagByMenu/1

post 申请即能够把参数放到申请体中,也能够把参数拼接到 url 尾部

2、后端接参形式

2.1 @PathVariable

前端传参如:http://localhost:9003/test/1/chen,须要应用此注解接管参数。

@RequestMapping("test/{id}/{name}")
public void test(@PathVariable("id") Long id ,@PathVariable("name") String name){System.out.println(id, name);
}
2.2 @RequestParam

前端 j 将参数拼接到 url 尾部的,如:http://localhost:9003/mid/app/queryTagByMenu?name=1,须要应用此注解接管参数。

如果应用此注解,则 url 中必须有这个参数,否则会报 400 谬误。

@PostMapping("/queryTagByMenu")
public AjaxResult queryTagByMenu(@RequestParam String menuId) {if (StringUtil.isEmpty(menuId)) {return AjaxResult.error("短少 menuId 参数");
  }
  return AjaxResult.success();}
2.3 @RequestBody

前端应用 post 形式,将参数写在 body 中的,能够依照属性名,应用 map 或者实体类接管。

@PostMapping("/queryMenuByRole")
public AjaxResult queryMenuByRole(@RequestBody AppMenuRoleVo appMenuRoleVo) {return AjaxResult.success(appSysService.queryMenuListByRole(appMenuRoleVo));
}
2.4 无注解接管参数

有人说无注解也能够失常接管参数,我试了一下,发现 post 是无奈接管参数的。

上面试试应用 get 传参数,发现 get 是能够主动组装成实体类的。

get 申请也实用于单参数无注解的状况。

2.5 @RequestHeader @CookieValue

这两个用法都差不多,我用的比拟少,基本上如果我须要从 header 中获取参数的话,个别我是从 request 中获取。

@GetMapping("/test")
public void demo3(@RequestHeader(name = "headerName") String headerName,
  @CookieValue(name = "cookieName") String cookieName) {System.out.println(myHeader + "--" + cookieName);
}

看到这里,大家大略对前后端参数传递有了一些理解,欢送留言探讨。

集体博客:https://www.51bishe.site

退出移动版