The Controller development environment in this article is shown in the following table

System/Tools The version number
OS Windows 7 Home Basic
Java 1.7.0 _79
Eclipse Mars. 1 Release (4.5.1)
Maven 3.3.9
Postman 4.8.1
Tomcat 7.0.47

Maven mainly depends on configuration for Pom

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>This will RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>This will RELEASE</version>
</dependency>Copy the code

Basic data types

SpringMVC Controller method parameter bindings first support all Java primitive types (including: byte, short, int, long, float, double, char, String, Boolean), and primitive types corresponding to encapsulated advanced classes (including: StringBuilder, StringBuffer.

The code example is as follows (only int and Integer are used as examples, and the other types are implemented the same way) :

@Controller
@RequestMapping("param")
public class ParamController {
    @RequestMapping(value="/int", method=RequestMethod.POST)
    @ResponseBody
    public String requestInt(int param) {
        return "Request successful. Post param : Int - " + param;
    }
    @RequestMapping(value="/integer", method=RequestMethod.POST)
    @ResponseBody
    public String requestInteger(Integer param) {
        return "Request successful. Post param : Integer - " + param;
    }
    / /...
}Copy the code

Collection types

  • List

RequestParam() = RequestParam(); RequestParam() = RequestParam(); Specific code examples are as follows:

@RequestMapping(value="/list", method=RequestMethod.POST)
@ResponseBody
public String requestList(@RequestParam("listParam[]") List<String> param) {
    return "Request successful. Post param : List<String> - " + param.toString();
}Copy the code

The Postman request is as follows:





Postman Post request and reply icon. PNG

The Ajax request is as follows:

var strList = new Array(a); strList.push("field1");
strList.push("field2");
function postList() {
    $.ajax({
        type:"POST".url:"http://localhost:8080/Learn-Spring-MVC/list".data: {"listParam" : strList},
        dataType:"json".success:function(result) {
            / /...
        },
        error:function(result) {
            / /...}}); }Copy the code

As for List as a Controller parameter, except for String, I also test Integer and Double. Other types are not tested. @requestParam () must add “listParam[]” if you have a different name for your Web server. If you only use @requestParam, The request is prompted with HTTP Status 400 – Required List parameter ‘XXX’ is not present.

  • Map

RequestParam (@requestParam, @requestParam, @requestParam, @requestParam, @requestParam, @requestParam)

@RequestMapping(value="/map", method=RequestMethod.POST)
@ResponseBody
public String requestList(@RequestParam Map<String.Object> param) {
    return "Request successful. Post param : Map - " + param;
}Copy the code

The Postman request is as follows:





Postman Post request and reply icon. PNG

The Ajax request is as follows:

function postMap(a) {
    $.ajax({
        type:"POST",
        url:"http://localhost:8080/Learn-Spring-MVC/map",
        data:{field1:"field1",field2:1},
        dataType:"json",
        success:function(result) {
            / /...
        },
        error:function(result) {
            / /...}}); }Copy the code

Map converts all the data in the Ajax request to key-values and stores them in the Map. See @requestParam in the Spring documentation for details

Custom type

Customize the People class. The specific content of the class is shown in the code below:

public class People implements Serializable{
    private static final long serialVersionUID = 1L;
    private String name;
    private short age;
    private Map<String, String> relationship;
    public String getName(a) {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public short getAge(a) {
        return age;
    }
    public void setAge(short age) {
        this.age = age;
    }
    public Map<String, String> getRelationship(a) {
        return relationship;
    }
    public void setRelationship(Map<String, String> relationship) {
        this.relationship = relationship;
    }
    @Override
    public String toString(a) {
        return "People [name=" + name + ", age=" + age + ", relationship=" + relationship + "]"; }}Copy the code

The corresponding Controller method code is shown below. The main difference is that the @modelAttribute annotation needs to be added before the custom class:

@RequestMapping(value="/people", method=RequestMethod.POST)
@ResponseBody
public String requestPeople(@ModelAttribute People people) {
    return "Get request is successful. Post param : User Class - " + people.toString();
}Copy the code

The Ajax request is as follows:

  var people = {
    name:"Heacewalker".age:25.relationship: {"boss":"BigBoss"}}function postClick() {
    $.ajax({
      type:"POST".url:"http://localhost:8080/Learn-Spring-MVC/people".data:people,
      dataType:"json".success:function(result) {
          / /...
      },
      error:function(result) {
          / /...}}); }Copy the code

The Postman request is as follows:





Postman Post request and reply icon. PNG

If a custom class contains a collection, you can define a class that contains a collection as follows:

public class Address {
    private String code;
    private String address;
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    @Override
    public String toString() {
        return "Address [code=" + code + ", address=" + address + "]"; }}Copy the code

public class Link {
    private List<Address> address;
    public List<Address> getAddress(a) {
        return address;
    }
    public void setAddress(List<Address> address) {
        this.address = address;
    }
    @Override
    public String toString(a) {
        return "Link [address=" + address + "]"; }}Copy the code

Finally, the code for the Controller section is shown as follows:

    @RequestMapping(value="/link", method=RequestMethod.POST)
    @ResponseBody
    public String requestLink(@ModelAttribute Link link) {
        return "Get request is successful. Post param : User Class - " + link.toString();
    }Copy the code




Postman Post request and reply icon. PNG

The Postman request is as follows:





Postman Post request and reply icon. PNG

The Ajax request is as follows:

<form onsubmit="return PostData()">
    <input name="address[0].address" value="AKB"/>
    <input name="address[0].code" value="48"/>
    <input name="address[1].address" value="HKT"/>
    <input name="address[1].code" value="48"/>
    <input type="submit" value="Submit"/>
</form>
......
function PostData(a) {
    $.ajax({
        type:"POST",
        url:"http://localhost:8080/Learn-Spring-MVC/link",
        data:' ',
        success:function(result) {
            / /...
        },
        error:function(result) {
            / /...}}); }Copy the code

Pass the parameters through the URL path and receive them. The specific Controller code is as follows:

@RequestMapping(value="/path/{key}/{value}", method=RequestMethod.POST)
@ResponseBody
public String requestPath(@PathVariable String key, @PathVariable String value) {
    return "Get request is successful. Path param : key - " + key + "; value - " + value;
}Copy the code

The Postman request is as follows:





Postman Post request and reply icon. PNG

Finally, the method used to receive request parameters with HttpServletRequest is shown in the Controller code as follows. The Controller receives parameters of type String:

@RequestMapping(value="/request", method=RequestMethod.POST)
@ResponseBody
public String request(HttpServletRequest arg0, HttpServletResponse arg1) {
    return "Get request is successful. Post param : param1 - " + arg0.getParameter("param1") +
           "; param2 - " + arg0.getParameter("param2") + 
           "; param3 - " + arg0.getParameter("param3");
}Copy the code

Corresponding Ajax request:

  var idList = new Array(a); idList.push("1");
  idList.push("2");
  idList.push("3");
  function postTest() {
    $.ajax({
      type:"POST".url:"http://localhost:8080/Learn-Spring-MVC/request".data: {"param1":"test"."param2":2."param3":JSON.stringify(idList)},
      dataType:"json".success:function(result) {
        / /...
      },
      error:function(result) {
          / /...}}); }Copy the code

Here the idList is the collection type, and the values received to the Controller layer correspond to null if not converted with json.stringify ().

Resources: Various parameter bindings for SpringMVC