The problem of receiving set Integer in Spring MVC

topic description

Integer problem of receiving collections in Spring MVC

topic source

in response to the requirements of batch queries, the API is separated by commas when calling, and the entity object attribute List < Integer > is used in spring mvc . The framework will automatically separate and save the data.
if the data is a non-numeric value, an error will be reported, but if the data is a blank character and there is no data in the delimiter, the blank character will be saved as null , which is not in line with the expected effect. How can we deal with this situation?

related codes

@PostMapping("test")
@ResponseBody
public User test(User user) {
    return user;
}


public class User {
    private List<Integer> idList;

    public List<Integer> getIdList() {
        return idList;
    }

    public void setIdList(List<Integer> idList) {
        this.idList = idList;
    }
}

what result do you expect? What is the error message actually seen?

the actual expected result is to ignore blank characters and empty data, or to indicate that the data is incorrect if it cannot be ignored.

normal result 1

enter the correct data
clipboard.png

2

clipboard.png

1

clipboard.png

clipboard.png

2


clipboard.png

Mar.28,2021

@InitBinder
public void initBinder(WebDataBinder binder) {
    binder.registerCustomEditor(List.class,new PropertyEditorSupport() {
        @Override
        public void setAsText(String text) {
            this.setValue(text);
        }
    });
}

use SpringMVC's data binding to initialize data binding when the request parameter arrives
customize the operation in the setAsText method according to your own needs

Menu