JavaWeb 接收Request请求参数的几种方式

x33g5p2x  于2022-02-07 转载在 Java  
字(1.6k)|赞(0)|评价(0)|浏览(786)

JavaWeb 接收Request请求参数的几种方式

1. HttpServletRequest request接收参数

  1. @RequestMapping("/test1")
  2. public String test1(HttpServletRequest request) {
  3. User user = new User();
  4. user.setName(request.getParameter("name"));
  5. user.setAge(Integer.valueOf(request.getParameter("age")));
  6. user.setMoney(Double.parseDouble(request.getParameter("money")));
  7. return JSON.toJSONString(user);
  8. }

最原始的接收参数方式,可以接收url params 传参,支持post from类型传参,不支持JSON传参

2. 接收url地址中的参数

  1. @RequestMapping(value = "/test2")
  2. public String test2(@RequestParam("name") String name,
  3. @RequestParam("age") Integer age
  4. ) {
  5. return name;
  6. }

这种格式接收的是 /test2?name=zhangsan&age=15 格式的传参

@RequestParam 如果不写,就要求跟url地址中携带的参数名完全一致

这种形式传参与请求方式无关,Get,Post,Put 等皆可

3. 直接通过对象接收

  1. @RequestMapping(value = "/test3")
  2. public String test3(User user) {
  3. return JSON.toJSONString(user);
  4. }

这种方式要求请求中的参数名与实体中的属性名一致即可自动映射到实体属性中;

支持url拼接的多个params 传参

支持post请求 的form类型传参(form-data,x-www-form-urlencoded),不支持JSON 传参

4. @RequestBody 接收body中的JSON字符串参数

  1. @PostMapping(value = "/test4")
  2. public String test4(@RequestBody User user) {
  3. return JSON.toJSONString(user);
  4. }

@RequestBody 是接收请求体中的JSON 字符串参数直接映射实体对象,所以body类型必须是JSON字符串;而且实体类中的属性名称必须与JOSN串中的参数key名称完全一致,不同命参数无法正确接收;

此种传参方式,推荐使用 Post请求

5. @PathVariable RestFul 风格传参

  1. @RequestMapping(value = {"/test5/{name}/{age}"})
  2. public String method07(@PathVariable("name") String name,
  3. @PathVariable(value = "age", required = false) Integer age
  4. ) {
  5. User user = new User();
  6. user.setName(name);
  7. user.setAge(age);
  8. return JSON.toJSONString(user);
  9. }

/test5?/zhangsan/25

通过 @PathVariable 实现 RestFul 风格传参,直接将参数拼接到url地址中,支持Get,Post,Put,Delete 等多种请求

required属性默认为true,不传递参数会报错;

如果出现某个参数可以不传递的情况,可以通过设置required属性为false

相关文章

最新文章

更多