Home > Net >  how to check the list is not null in spring boot rest request entity
how to check the list is not null in spring boot rest request entity

Time:05-21

I have a rest request entity in spring boot controller define like this:

package com.dolphin.rpa.application.command.credential;

import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.List;

/**
 * @author xiaojiang.jiang
 * @date 2022/05/10
 **/
@Data
public class CredentialDeleteCommand {
    @NotNull(message = "should not be null")
    private List<Long> ids;

    @Min(1)
    @Max(2)
    private Integer mode;

}

Now I want to make sure the ids should not be null or size eqauls 0. I have tried these way:

    @NotNull(message = "should not be null")
    @NotEmpty(message = "should not be null")
    @NotBlank(message = "should not be null")

But could not work. I also read the official docs that did not mentioned valid the List. Is it possible to valid the List elemnts? This is my reqeust json:

{
    "ids": [
        
    ],
    "mode": 1
}

CodePudding user response:

Just adding @Size(min=1) is enough.

@Data
public class CredentialDeleteCommand {
    @NotNull(message = "should not be null")
    @Size(min=1)
    private List<Long> ids;

    @Min(1)
    @Max(2)
    private Integer mode;

}

The error is probably where you call this object to be validated. It must certainly be on some method from an instance that belongs to spring. So it should be a bean of spring container.

Normally you will use this in some method of the controller, as the controller already belongs to spring container.

    @RequestMapping(path="/some-path",method=RequestMethod.POST)
    public ResponseEntity doSomething(@Valid @RequestBody CredentialDeleteCommand credentialDeleteCommand){
    ....
    }

Keep in mind though that @Valid should be placed before @RequestBody otherwise it does not work. At least in previous spring versions that I have faced this issue.

CodePudding user response:

How is this?

@Size(min=1)
private List<Long> ids;

CodePudding user response:

@Size or @NotNull should do the job if this dependency

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

is specified.

Also dont forget about @Valid annotation.

Another way for arrays is to init them in model, so even if it's not specified in requestbody, you will get it initialized anyway.

  • Related