Several common ways SpringBoot reception parameters (reproduced)

Reproduced

First class: the request path parameter

1, @ PathVariable

Get the path parameters. I.e. url / {id} in this form.

2、@RequestParam

Get query parameters. That url? Name = this form

Examples of
the GET
HTTP: // localhost:? 8080 / Demo / 123 = suki_rong name
Java codes corresponding to:

@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);
}

Output: 
ID = 123 
name = suki_rong

The second category: Body Parameters

Because POST request, where a theme Postman binding Code Description

1、@RequestBody

example

 

 

 

 Java code corresponding to:

@PostMapping(path = "/demo1")
public void demo1(@RequestBody Person person) {
    System.out.println(person.toString());
}

Output: 

name:suki_rong;age=18;hobby:programing

It may be so

@PostMapping(path = "/demo1")
public void demo1(@RequestBody Map<String, String> person) {
    System.out.println(person.get("name"));
}

Output: 

suki_rong

2, no comment

example

Person class:

public class Person {

    private long id;
    private String name;
    private int age;
    private String hobby;

    @Override
    public String toString(){ return "name:"+name+";age="+age+";hobby:"+hobby; } // getters and setters }

 

 

 

 Java code corresponding to:

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

Output: 

name:suki_rong;age=18;hobby:programing

 

The third category: Cookie request header parameter and

1、@RequestHeader

2, @ Cookie Value

example

java code:

@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);
}

It can be so

@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());
        }
    }
}

 

This article CSDN blogger "suki_rong" of the original article, the original link: https: //blog.csdn.net/suki_rong/article/details/80445880

 

Guess you like

Origin www.cnblogs.com/jyiqing/p/12470238.html
Recommended