Gyh's blog

vuePress-theme-reco gyh    2022
Gyh's blog Gyh's blog

Choose mode

  • dark
  • auto
  • light
Home
Category
  • Algorithm
  • CSS
  • JavaScript
  • Others
  • Server
  • Utils
  • Article
  • Note
  • Git
  • Npm
  • Standard
  • Summary
Tag
Timeline
About
GitHub
author-avatar

gyh

91

Article

11

Tag

Home
Category
  • Algorithm
  • CSS
  • JavaScript
  • Others
  • Server
  • Utils
  • Article
  • Note
  • Git
  • Npm
  • Standard
  • Summary
Tag
Timeline
About
GitHub

SpringBoot Controller接收参数的几种常用方式

vuePress-theme-reco gyh    2022

SpringBoot Controller接收参数的几种常用方式

gyh 2018-09-09

# 第一类:请求路径参数

  • @PathVariable

获取路径参数。即url/{id}。

  • @RequestParam

获取查询参数。即url?name=我是渣渣辉

# 例子

GET http://localhost:8080/demo/1?name=我是渣渣辉 对应的 java 代码:

@GetMapping("/demo/{id}")
public void demo(@PathVariable(name = "id") String id, @RequestParam(name = "name") String name) {
    System.out.println("id="+id);
    System.out.println("name="+name);
}
1
2
3
4
5

输出结果: id=1 name=我是渣渣辉

# 第二类:Body 参数

'content-type' : application/json

@PostMapping(path = "/demo")
public void demo1(@RequestBody Person person) {
    System.out.println(person.toString());
}
1
2
3
4
@PostMapping(path = "/demo")
public void demo1(@RequestBody Map<String, String> person) {
    System.out.println(person.get("name"));
}
1
2
3
4

'content-type' : form-data

@PostMapping(path = "/demo2")
public void demo2(Person person) {
    System.out.println(person.toString());
}
1
2
3
4

'content-type' :x-www-form-urlencoded

multipart/form-data与x-www-form-urlencoded的区别:
 multipart/form-data:可以上传文件或者键值对,最后都会转化为一条消息
 x-www-form-urlencoded:只能上传键值对,而且键值对都是通过&间隔分开的。
1
2
3

# 第三类:请求头参数以及 Cookie

@GetMapping("/demo3")
public void demo3(@RequestHeader(name = "myHeader") String myHeader,
        @CookieValue(name = "myCookie") String myCookie) {
    System.out.println("myHeader=" + myHeader);
    System.out.println("myCookie=" + myCookie);
}
1
2
3
4
5
6

或者

@GetMapping("/demo3")
public void demo3(HttpServletRequest request) {
    System.out.println(request.getHeader("myHeader"));
    for (Cookie cookie : request.getCookies()) {
        if ("myCookie".equals(cookie.getName())) {
            System.out.println(cookie.getValue());
        }
    }
}
1
2
3
4
5
6
7
8
9
Edit on GitHub~
LastUpdated: 5/17/2022, 8:59:22 AM