Encapsulate various parameters of Spring MVC

Table of contents

1. Simple data types

1.1 Controller method

1.2 Test results

2. Object type

2.1 Single object

2.1.1 Controller methods

2.1.2 Test results

2.2 Associated objects

2.2.1 Controller methods

2.2.2 Test results

3. Collection type

3.1 Collection of simple data types

3.1.1 Control method

3.1.2 Test results

3.2 Collection of object data types

3.2.1 Controller methods

3.2.2 Test results

3.3 Map collection

3.3.1 Controller methods

3.3.2 Test results 

Related readings of previous columns & articles 

1. Maven series of columns

2. Mybatis series of columns

3. Spring series of columns 

4. Spring MVC series of columns  


1. Simple data types

In Servlet, we get request parameters through request.getParameter(name). There are two problems with this method:

  1. Code redundancy occurs when there are many request parameters.
  2. tightly coupled with the container

SpringMVC supports parameter injection to obtain request data, that is, request parameters are directly encapsulated into method parameters. The usage is as follows:

1.1 Controller method

// 获取简单类型参数
    @RequestMapping("/c1/param1")
    public void simpleParam(String username,int age){
        System.out.println(username+" "+age);
    }

        Since we have not configured the corresponding param1 page, this is to directly print out the accessed parameters on the console. When accessing this method, the request parameter name is the same as the method parameter name to complete automatic encapsulation. and print it out on the console. The execution path is: http://localhost:8080/c1/param1?username=LYL&age=19

1.2 Test results

OK, it is indeed successfully output on the console, indicating that the encapsulation is successful. Next, let's talk about the object type. 

2. Object type

SpringMVC supports directly encapsulating parameters as objects. First, we create a new student class. as follows:

Student 

package com.example.domain;


public class Student {
    private int id;
    private String name;
    private String sex;

    public Student() {
    }

    public Student(int id, String name, String sex) {
        this.id = id;
        this.name = name;
        this.sex = sex;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    @Override
    public String toString() {
        return "Student[ " +
                "id=" + id +
                ", name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                " ]";
    }
}

2.1 Single object

2.1.1 Controller methods

// 获取对象类型参数
    @RequestMapping("/c1/param2")
    public void objParam(Student student){
        System.out.println(student);
    }

 You can know that we will print out the specific information of the students on the console,

Access path: http://localhost:8080/c1/param2?id=1&name=LYL&sex=man

2.1.2 Test results

        OK, it is indeed printed on the console, indicating that when we encapsulate the object type, we only need to put their attributes in the parameters of the access path 

2.2 Associated objects

        To realize the encapsulation of associated objects, first we have to create an Address address class, and then add an Address type attribute in the Student class. as follows:

Address: 

package com.example.domain;

public class Address {

    // 地址信息
    private String info;
    // 邮编
    private String postcode;

    public String getInfo() {
        return info;
    }

    public void setInfo(String info) {
        this.info = info;
    }

    public String getPostcode() {
        return postcode;
    }

    public void setPostcode(String postcode) {
        this.postcode = postcode;
    }

    @Override
    public String toString() {
        return "Address[ " +
                "info='" + info + '\'' +
                ", postcode='" + postcode + '\'' +
                " ]";
    }
}

 Remember to modify the Student class as follows:

package com.example.domain;

import java.util.List;
import java.util.Map;

public class Student {
    private int id;
    private String name;
    private String sex;
    // 地址对象
    //private Address address;

    public Student() {
    }

    public Student(int id, String name, String sex) {
        this.id = id;
        this.name = name;
        this.sex = sex;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "Student[ " +
                "id=" + id +
                ", name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                ", address='" + address + '\'' +
                " ]";
    }
}

2.2.1 Controller methods

    // 获取关联对象类型参数
    @RequestMapping("c1/param3")
    public void objParam2(Student student){
        System.out.println(student);
    }

        When accessing this method, the request parameter name is the same as the attribute name of the method parameter, and then automatic encapsulation can be completed. , so we can write the request path as: http://localhost:8080/c1/param3?id=1&name=HQX&sex=woman&address.info=guangzhou&address.postcode=5201314

2.2.2 Test results

OK, it can be clearly seen that it can be successfully queried. 

3. Collection type

        SpringMVC supports the encapsulation of parameters as a List or Map collection. The following demonstrates how to encapsulate a collection of simple data types. as follows:

3.1 Collection of simple data types

3.1.1 Control method

// 绑定简单数据类型List参数,参数前必须添加@RequestParam注解
    @RequestMapping("/c/param4")
    public void listParam(@RequestParam List<String> users){
        users.forEach(System.out::println);
    }

It can be seen from the code that this collection will be traversed in the console after access.

The access path is as follows:  http://localhost:8080/c/param4?users=LYL&users=HQX

3.1.2 Test results

 OK, indeed successfully printed out on the console.

3.2 Collection of object data types

        SpringMVC does not support encapsulating parameters into a List collection of object type, but it can be encapsulated into an object with a List property. Here we have to add a collection object to the Student class first. It is written as follows:

Student

package com.example.domain;

import java.util.List;
import java.util.Map;

public class Student {
    private int id;
    private String name;
    private String sex;

    // 地址集合List
    private List<Address> address;

    public Student() {
    }

    public Student(int id, String name, String sex) {
        this.id = id;
        this.name = name;
        this.sex = sex;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public List<Address> getAddress() {
        return address;
    }

    public void setAddress(List<Address> address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "Student[ " +
                "id=" + id +
                ", name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                ", address='" + address + '\'' +
                " ]";
    }
}

3.2.1 Controller methods

// 对象中包含集合属性
    @RequestMapping("c1/param6")
    public void listParam6(Student student){
        System.out.println(student);
    }

In fact, it is no different from the above object types, mainly because the attributes of the parameter types are different, and the access paths are different. 

访问路径:http://localhost:8080/c1/param6?id=1&name=LYL&sex=man&address[0].info=HQX&address[0].postcode=520&address[1].info=MVC&address[1].postcode=1314

3.2.2 Test results

 OK, it can also be successfully queried

3.3 Map collection

        Similarly, if SpringMVC wants to encapsulate the Map collection, it needs to be encapsulated into an object with a Map attribute. Modify the Student entity class as follows:

Student

package com.example.domain;

import java.util.List;
import java.util.Map;

public class Student {
    private int id;
    private String name;
    private String sex;

    // 地址集合Map
    private Map<String,Address> address;

    public Student() {
    }

    public Student(int id, String name, String sex) {
        this.id = id;
        this.name = name;
        this.sex = sex;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public Map<String, Address> getAddress() {
        return address;
    }

    public void setAddress(Map<String, Address> address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "Student[ " +
                "id=" + id +
                ", name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                ", address='" + address + '\'' +
                " ]";
    }
}

3.3.1 Controller methods

// 对象中包含Map属性
    @RequestMapping("c1/param7")
    public void mapParam(Student student){
        System.out.println(student);
    }

Access path:

http://localhost:8080/c1/param7?id=1&name=LYL&sex=man&address[%27one%27].info=H&address[%27one%27].postcode=520&address[%27two%27].info=QX&address[%27two%27].postcode=1314]

3.3.2 Test results 

        OK, it was also successfully detected. As for why the info of the first two is empty, it is because I missed a ']', so there was a little episode, but it does not affect our continued output.

Related readings of previous columns & articles 

     If you don’t know anything about the content of this issue, you can also go to the previous issues. The following is a series of column articles such as Maven and Mybatis carefully crafted by bloggers in the past. Don’t miss it when you pass by! If it is helpful to you, please like it and bookmark it. Among them, some of the Spring columns are being updated, so they cannot be viewed, but they can be viewed after the bloggers have completed all the updates.

1. Maven series of columns

Maven Series Column Maven project development
Maven aggregation development [example detailed explanation --- 5555 words]

2. Mybatis series of columns

Mybatis series column MyBatis entry configuration
Mybatis entry case [super detailed]
MyBatis configuration file - detailed explanation of related tags
Mybatis fuzzy query - three methods of defining parameters and aggregation query, primary key backfill
Mybatis dynamic SQL query -- (attached actual combat case -- 8888 words -- 88 quality points)
Mybatis paging query - four ways to pass parameters
Mybatis first level cache and second level cache (with test method)
Mybatis decomposition query
Mybatis related query [attached actual combat case]
MyBatis annotation development --- realize addition, deletion, modification and dynamic SQL
MyBatis annotation development --- realize custom mapping relationship and associated query

3. Spring series of columns 

Spring series column Introduction to getting started with Spring IOC [custom container instance]
IOC uses Spring to implement detailed explanation with examples
The creation method, strategy, destruction timing, life cycle and acquisition method of Spring IOC objects
Introduction to Spring DI and Dependency Injection Method and Dependency Injection Type
Application of Spring IOC-related annotations——Part 1
Application of Spring IOC-related annotations——Part 2
Introduction to Spring AOP and related cases
Annotation, native Spring, and SchemaBased implement AOP in three ways [with detailed case]
Introduction to Spring affairs and related cases
Spring transaction management scheme and transaction manager and transaction control API
Spring transaction related configuration, propagation behavior, isolation level and annotation configuration declarative transaction

4. Spring MVC series of columns  

SpringMVC series column Introduction to Spring MVC with an introductory case
Spring MVC various parameter acquisition and acquisition methods custom type converter and encoding filter
Spring MVC gets parameters and custom parameter type converters and encoding filters
Spring MVC processing response with detailed case explanation
Application of Spring MVC-related annotations—— Part 1

Application of Spring MVC-related annotations - Part 2

Application of Spring MVC-related annotations——Part 2
File upload in multiple situations of Spring MVC
Spring MVC asynchronous upload, cross-server upload and file download
Spring MVC exception handling [single control exception handler, global exception handler, custom exception handler]
Spring MVC interceptors and cross domain requests
SSM integration case [the case of station C explaining the most detailed process]

Guess you like

Origin blog.csdn.net/qq_53317005/article/details/130372221