[Java Foundation] How to accept an array or collection in the background by the front end (case details)

[ChenRen tries hard]: hello, I'm ChenRen. I'm glad you can read it. Nickname is that I hope I can keep improving and move forward to excellent programmers!

The blog comes from the summary of problems encountered in the project and programming. Occasionally there will be reading and sharing. I will update the summary of relevant knowledge points such as Java front-end, background, database, project cases and so on. Thank you for your reading and attention. I hope my blog can help more people, share new knowledge and progress together!

We quarryers, with the heart of the cathedral, wish you all to run in your own love.

1. Basic Learning

hello continues to share Java-based background acceptance of arrays and collections as real-world cases for beginners

First, let's simulate creating an instance of user

/**
 * @program: demo
 * @description: Ordinary user
 * @author: Chen Ling Should Make Efforts
 * @create: 2021-10-03 11:04
 */
@Data
public class User {

    private String id;
    private String name;
    private Integer age;

}

Create a common return value help class

import lombok.Data;

/**
 * @program: demo
 * @description: Encapsulate common return values
 * @author: Chen Ling Should Make Efforts
 * @create: 2021-10-03 11:05
 */
@Data
public class Result<T> {

    private static final long serialVersionUID = 1L;

    private Integer code;
    private String msg;
    private T data;

    public static Result fail() {
        Result Result = new Result();
        Result.setCode(1);
        Result.setMsg("Server error!!!");
        return Result;
    }

    public static Result fail(String msg) {
        Result Result = new Result();
        Result.setCode(1);
        Result.setMsg(msg);
        return Result;
    }

    public static <T> Result success(T data) {
        Result Result = new Result();
        Result.setCode(0);
        Result.setData(data);
        return Result;
    }

    public static Result success() {
        Result Result = new Result();
        Result.setCode(0);
        Result.setMsg("Operation successful!");
        Result.setData("success");
        return Result;
    }


}

Business Scenario One: How does the front-end object collection work behind the scenes?

[
	{
	   "id":"1",
	   "name":"Chen Lu",
	   "age":"22"
     },
	{
	   "id":"2",
	   "name":"Chen Ling Should Make Efforts",
	   "age":"23"
     }
]

Background acceptance

@RequestBody List<User> userList

Business Scenario 2: How does the front-end transfer array work behind the scenes?

["2021","2022"]

Background acceptance

@RequestBody List<String> list

Simple write a controller layer to simulate business operations: Re-view entry

/**
 * @program: demo
 * @description: Front-End Value-Passing Interaction Case
 * @author: Chen Ling Should Make Efforts
 * @create: 2021-10-03 11:09
 */
@RestController
@RequestMapping("/user")
public class UserController {

    //Print Log
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    /**
     * Front-end object collection Back-end joins with collection
     * @param userList
     * @return
     */
    @PostMapping("/saveList")
    public Result saveUserList(@RequestBody List<User> userList) {

        logger.info("The parameter passed in is{}",userList);

        //Simulate Logic Layer as a Participation Check
        if (CollectionUtils.isEmpty(userList)){
            return Result.fail();
        }
        return Result.success();
    }

    /**
     * Business Scenario: Front end passes in a separate array
     * @param list
     * @return
     */
    @PostMapping("/saveUserIds")
    public Result saveStrings(@RequestBody List<String> list) {

        logger.info("The parameter passed in is{}",list);
        //Simulate Logic Layer as a Participation Check
        if (CollectionUtils.isEmpty(list)){
            return Result.fail();
        }
        return Result.success();
    }

}

Business Scenario 1: The collection backend of the front-end object is accepted with the corresponding list

Business Scenario 2: Front End Transfer Corresponding Array Background Acceptance

See the parameters for console printing

Successfully accept a collection or array from the front end using the method above

2. Advanced Learning

Have you ever encountered a problem where the front end passes properties like a string or a number in addition to a collection?

Business Scenario: The incoming collection represents the data to be manipulated, the incoming string, strings/numbers differ from business logic, etc.

Participation cases are as follows

{
	"userList":[{"id ":"1","name":"Chen Lu","age":"22"},{"id":"2","name":"Chen Ling Should Make Efforts","age":"23"}],
    "open":1
}

Acceptance: Create an object to accept

/**
 * @program: demo
 * @description: User Object Acceptance Class
 * @author: Chen Ling Should Make Efforts
 * @create: 2021-10-03 11:04
 */
@Data
public class UserVo {

    private List<User> userList;
    private Integer open;
}

Practice cases are as follows

/**
 * @program: demo
 * @description: Front-End Value-Passing Interaction Case
 * @author: Chen Ling Should Make Efforts
 * @create: 2021-10-03 11:09
 */
@RestController
@RequestMapping("/user")
public class UserController {

    //Print Log
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    /**
     * Business Scenario: Front-end passes an array➕A string or number, etc.
     * @param userVo
     * @return
     */
    @PostMapping("/saveUserVo")
    public Result saveUserVoList(@RequestBody UserVo userVo) {

        logger.info("The parameter passed in is{}",userVo);

        return Result.success();
    }
}

We can debug to see the parameters and clearly see the parameters passed in from the front end

For front-end and back-end parameters, the most important thing is to unify the corresponding parameter attribute names, methods of parameter transmission, etc. If you confirm them well in advance, the development efficiency will be greatly improved.


Answer: In addition to passing a set, the front-end also passes a string or a number and other attributes. We can solve the above problem by creating a VO object to accept it.

hello,Hello, my name is Chenle. I will continue to tidy up later Java Basic related cases, I hope to help more beginners, welcome to learn, share, communicate, punch in!

Thank you very much for reading this article. If this article helps you, I hope to leave some comments on it.👍 follow❤Share👥 Leaving a message.💬thanks!!!

October 4, 2021 22:52:21 May you run in your own love!

Keywords: Java Spring RESTful

Added by Sakujou on Tue, 05 Oct 2021 03:05:59 +0300