Spring MVC parameter binding details

summary

I remember when I was debugging the interface with my front-end colleagues, the back-end spring MVC needed to receive the parameters of the array type, and then told the front-end that it needed to pass the array type. Later, the front-end children's shoes passed the array, but the back-end reception was unsuccessful and the joint debugging failed. At that time, due to the time, I didn't study this carefully. At that time, I thought of a way that the front end passed a json string, and the back end received the json string and then converted it into the required array object. This is obviously not a good practice. We didn't use what the framework helped us do well, and there were two more data transformations for nothing. So today I spent some time to study and summarize the data binding of spring MVC.

1. Simple type parameters

That is, several java Native basic data types have their encapsulated classes and String types. Relatively simple, choose a boolean type to explain.
Test code:

    @RequestMapping(value = "test")
    @ResponseBody
    public Object testDataBind(@RequestParam(name = "test") Boolean test) {
        System.out.println(test);
        return "success";
    }

To send a request using the postman tool:

Console output:

true1

This is relatively simple, there is not much to say** It should be noted here that if the parameter is not annotated with @ RequestParam, the name of the default parameter test is required as the name of the parameter. Moreover, if it is not annotated, the front end can not transmit the parameter and will not report an error when sending an http request. However, if the annotation is added, the parameter must be passed without setting the attribute required = false of the annotation, otherwise a 400 error will be reported. If the name attribute is specified in the annotation, the name front-end needs to take the value of name as the front-end parameter name. If the name attribute is not specified, test is the front-end parameter name according to the parameter name** You can verify it one by one.

2. Simple type array / list

There are two cases:

1) Directly using array as the parameter of the method can be modified with @ RequestParam annotation. If using List, it must be modified with @ RequestParam annotation

Interface code:

    @RequestMapping(value = "test")
    @ResponseBody
    public Object testDataBind(String[] tests) {
        System.out.println(tests[0] + "    " + tests[1]);
        return "success";
    }

This front-end parameter transfer needs to follow a certain format.

  • Form form
    The value of form element name must be the same
name="tests" value="arony1"
name="tests" value="arony2"12

postman send request:

Console output:

arony1    arony21
  • ajax
    The values of each element of the array should be separated by ",".
data:{"tests":"arony1,arony2"}1

It is worth noting that if the springMVC method parameters of the back end are received by array and the front end sends the request by ajax, the parameters can only be passed in the above format. It is not possible to use tests [0] and tests [1] to pass parameters.
postman send request:

Console output:

arony1    arony21

2) Use a custom class to encapsulate an array or List, and use the custom class instance as the method parameter, which cannot be modified with @ RequestParam annotation

Interface code:

    @RequestMapping(value = "test")
    @ResponseBody
    public Object testDataBind(Person person) {
        System.out.println(person.getTests()[0] + "    " + person.getTests()[1]);
        return "success";
    }

Person:

    public class Person {

        private String[] tests;

        public String[] getTests() {
            return tests;
        }

        public void setTests(String[] tests) {
            this.tests = tests;
        }
    }
  • Form form

There are two ways to transfer values

name="tests" value="arony1"
name="tests" value="arony2"12
name="tests[0]" value="arony1"
name="tests[1]" value="arony2"12

postman send request:

Console output:

arony1    arony21
  • ajax

    ajax can also pass values in two ways:

data:{"tests":"arony1,arony2"}1
data:{"tests[0]":"arony1","tests[1]":"arony2"}1

The effect is exactly the same as the form.

3. User defined type

First, define a custom type User, including the following properties, and generate the get/set method and toString method:

    private Integer id;
    private String loginname;12

Interface code:

    @RequestMapping(value = "test")
    @ResponseBody
    public Object testDataBind(User user) {
        System.out.println(user);
        return "success";
    }

postman send request:

Console output:

User{id=1, loginname='arony'}1

It can be seen that parameters with the same User attribute name can be accepted by the User object if they pass a value, and those not passed are the default values.
Let's try and annotate the parameter user with @ RequestParam. If you send a request using postman, you will find that 400 is returned. Therefore, we need to understand the meaning of @ RequestParam annotation, which indicates that the method parameter accepts an http parameter. Therefore, if you use a custom object as a parameter, do not add @ RequestParam before it, because spring MVC cannot convert the received parameter into a user object when parsing the parameter user of the http request.

4. Custom type array / list

Note: in this case, only one custom class can be used to wrap the array / list.
Define another parameter class:

public class Parameter {

    private Person[] person;

    public Person[] getPerson() {
        return person;
    }

    public void setPerson(Person[] person) {
        this.person = person;
    }
}

Person:

public class Person {

    private String tests;

    public String getTests() {
        return tests;
    }

    public void setTests(String tests) {
        this.tests = tests;
    }
}

Interface code:

    @RequestMapping(value = "test")
    @ResponseBody
    public Object testDataBind(Parameter parameter) {
        System.out.println(parameter.getPerson()[0].getTests() + "    " + parameter.getPerson()[1].getTests());
        return "success";
    }
  • form transfer parameters
name="person[0].tests" value="arony1"
name="person[1].tests" value="arony2"12
  • ajax parameters
data:{"person[0].tests":"arony1","person[1].tests":"arony2"}1

postman send request:

Console output:

arony1    arony21

5. Map < string, basic type >

As above, only one custom class can be used to wrap the map.

Parameter:

public class Parameter {

    private Map<String, String> map;

    public Map<String, String> getMap() {
        return map;
    }

    public void setMap(Map<String, String> map) {
        this.map = map;
    }
}

Interface code:

    @RequestMapping(value = "test")
    @ResponseBody
    public Object testDataBind(Parameter parameter) {
        parameter.getMap().forEach((key, value) -> {
            System.out.println(key + "   " + value);
        });
        return "success";
    }

Front end parameter transfer format:

  • Form form
name="map[key1]" value="arony1"
name="map[key2]" value="arony2"
perhaps
name="map.key1" value="arony1"
name="map.key2" value="arony2"12345
  • ajax
data:{"map[key1]":"arony1","map[key2]":"arony2"}
perhaps
data:{"map.key1":"arony1","map.key2":"arony2"}123

postman send request:

Console output:

key1   arony1
key2   arony212

6. Map < string, custom class >

It's very similar to 5.
Parameter:

public class Parameter {

    private Map<String, Person> map;

    public Map<String, Person> getMap() {
        return map;
    }

    public void setMap(Map<String, Person> map) {
        this.map = map;
    }
}

Person:

public class Person {

    private String tests;

    public String getTests() {
        return tests;
    }

    public void setTests(String tests) {
        this.tests = tests;
    }
}

Interface code:

    @RequestMapping(value = "test")
    @ResponseBody
    public Object testDataBind(Parameter parameter) {
        parameter.getMap().forEach((key, value) -> {
            System.out.println(key + "   " + value.getTests());
        });
        return "success";
    }

Front end parameter transfer format:

  • Form form
name="map[key1].tests" value="arony1"
name="map[key2].test2" value="arony2"12

Notice here that name = "map key1. Tests "value =" arony1 "it is impossible to pass values like this. Square brackets are required.

  • ajax
data={"map[key1].tests":"arony1","map[key2].test2":"arony2"}1

Square brackets must also be used here.

To send a request using postman:

Console output:

key1   arony1
key2   arony212

summary

The above spring MVC parameter binding can be summarized as follows:

Among them, map < string, ① > the front end can also use "." Replace square brackets.

Tags: Java Front-end Spring MVC PostMan

Posted by elum.chaitu on Sun, 15 May 2022 23:11:01 +0300