Various ways for SpringBoot controller to obtain Post requests

0. Test tool postman

Download address: https://www.postman.com/downloads/

1. Receive Form data

1.1 basic receiving method

1.1.1 no notes

@PostMapping("/hello")
public String hello(String name, Integer age) {
    String str = "" + name + " : " + age;
    System.out.println(str);
    return str;
}

Test 1:

Test 2:

1.1.2 annotated

@PostMapping("/hello")
public String hello(@RequestParam("id") String name,@RequestParam("age") Integer age) {
    String str = "" + name + " : " + age;
    System.out.println(str);
    return str;
}

Test 1:

Test 2: error reporting

You can also set the default value and whether it is null

@PostMapping("/hello")
public String hello(@RequestParam(name = "id",required = false) String name,@RequestParam(name = "age",defaultValue = "100") Integer age) {
    String str = "" + name + " : " + age;
    System.out.println(str);
    return str;
}

No parameters:

1.2 use map to receive parameters

Same as get request

@PostMapping("/hello")
public String hello(@RequestParam Map<String,Object> params) {
    String str = "" + params.get("name") + " : " + params.get("age");
    System.out.println(str);
    return str;
}

1.3 receive an array

@PostMapping("/hello")
public String hello(String[] name) {
    String str = "";
    for (String s : name){
        str = str + s + " ";
    }
    System.out.println(str);
    return str;
}


If the parameter is empty, an error will be reported

1.4 using objects to receive parameters

1.4.1 an object

You can directly inject multiple parameters into the object through getter and setter methods

@PostMapping("/hello")
public String hello(User user) {
    String str = "" + user;
    System.out.println(str);
    return str;
}

User class

public class User {
    private String name;
    private Integer age;

    public User(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public User() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}


If the parameter names do not match

1.4.2 multiple objects

@PostMapping("/hello")
public String hello(User user, Phone phone) {
    String str = "" + user + " " + phone;
    System.out.println(str);
    return str;
}

Phone class

public class Phone {
    private String number;

    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }

    public Phone() {
    }

    @Override
    public String toString() {
        return "Phone{" +
                "number='" + number + '\'' +
                '}';
    }

    public Phone(String number) {
        this.number = number;
    }
}

1.4.3 specify parameter prefix when using object reception

@PostMapping("/hello")
public String hello(@ModelAttribute("u") User user, Phone phone) {
    String str = "" + user + " " + phone;
    System.out.println(str);
    return str;
}

@InitBinder("u")
private void initBinder(WebDataBinder binder){
    binder.setFieldDefaultPrefix("u.");
}

2. Receive string text data content type: text / plain

2.1 HttpServletRequest

If the Text is passed, we can get the input stream through HttpServletRequest to read the Text content.

@PostMapping("/hello")
public String hello(HttpServletRequest request) {
    ServletInputStream is = null;
    try {
        is = request.getInputStream();
        StringBuilder sb = new StringBuilder();
        byte[] buf = new byte[1024];
        int len = 0;
        while ((len = is.read(buf)) != -1) {
            sb.append(new String(buf, 0, len));
        }
        System.out.println(sb.toString());
        return "The obtained text content is:" + sb.toString();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (is != null) {
                is.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}

2.2 @RequstBody annotation

@PostMapping("/hello")
public String hello(@RequestBody String text) {
    String str = "" + text;
    System.out.println(str);
    return str;
}

3. Receive JSON data content type: application / JSON

@ requestbody must be added

3.1 using Map to receive data

We can use @ json as the parameter to convert the data. If we use @ json as the parameter:

@PostMapping("/hello")
public String hello(@RequestBody Map<String,Object> params) {
    String str = "" + params.get("name") + " = " + params.get("age");
    System.out.println(str);
    return str;
}

3.2 using Bean objects to receive data

3.2.1 single object

User class is the same as above

@PostMapping("/hello")
public String hello(@RequestBody User user) {
    String str = "" + user;
    System.out.println(str);
    return str;
}

3.2.2 multiple objects

The User class is not preceded by @ RequestBody

@PostMapping("/hello")
public String hello(User user, @RequestBody Phone phone) {
    String str = "" + user + " " + phone;
    System.out.println(str);
    return str;
}

phone class recognized User class not recognized

3.2.3 object array

@PostMapping("/hello")
public String hello(@RequestBody List<User> user) {
    String str = "";
    for (int i = 0; i < user.size(); i++) {
        str = str + user.get(i) + "\n";
    }
    System.out.println(str);
    return str;
}

4. Content type: application / x-www-form-urlencoded type

The basic data is the same as that in the Form, except for 4.5

4.1 simple use

4.1.1 no notes

@PostMapping("/hello")
public String hello(String name, Integer age) {
    String str = "" + name + " : " + age;
    System.out.println(str);
    return str;
}

Test 1:

Test 2:

4.1.2 annotated

@PostMapping("/hello")
public String hello(@RequestParam("id") String name,@RequestParam("age") Integer age) {
    String str = "" + name + " = " + age;
    System.out.println(str);
    return str;
}


report errors:

You can also set the default value and whether it is null

@PostMapping("/hello")
public String hello(@RequestParam(name = "id",required = false) String name,@RequestParam(name = "age",defaultValue = "100") Integer age) {
    String str = "" + name + " : " + age;
    System.out.println(str);
    return str;
}

4.2 using map to receive parameters

@PostMapping("/hello")
public String hello(@RequestParam Map<String,Object> params) {
    String str = "" + params.get("name") + " : " + params.get("age");
    System.out.println(str);
    return str;
}

4.3 receiving an array

@PostMapping("/hello")
public String hello(String[] name) {
    String str = "";
    for (String s : name){
        str = str + s + " ";
    }
    System.out.println(str);
    return str;
}

4.4 receiving object

4.4.1 an object

@PostMapping("/hello")
public String hello(User user) {
    String str = "" + user;
    System.out.println(str);
    return str;
}

4.4.2 multiple objects

@PostMapping("/hello")
public String hello(User user, Phone phone) {
    String str = "" + user + " " + phone;
    System.out.println(str);
    return str;
}

4.5 string reception

@PostMapping("/hello")
public String hello(@RequestBody String params) {
    String str = "" + params;
    System.out.println(str);
    return str;
}

5. Summary

5.1 @RequestParam

It is mainly used for form data and application/x-www-form-urlencoded in get requests and post requests
@RequestParam has three configuration parameters:

  • Required indicates whether it is required. The default value is true and must be.
  • defaultValue to set the default value of the request parameters.
  • Value is the parameter name of the receiving url (equivalent to the key value).

5.2 @RequestBody

The annotation @ requestBody receives parameters from the requestBody, that is, the request body.
It is generally used to process data in non content type: application / x-www-form-urlencoded encoding format, such as application/json, application/xml, text/plain and other types of data.

6. Reference

https://www.hangge.com/blog/cache/detail_2485.html
https://blog.csdn.net/qq_20957669/article/details/89227840
https://cloud.tencent.com/developer/article/1414464

7. Address of the first part

https://blog.csdn.net/jumpe_17/article/details/117125508

Keywords: Spring

Added by NewBob on Thu, 10 Feb 2022 03:18:13 +0200