如何以简单的方式检查请求正文是否为空或请求正文是否具有空字段?

问题描述 投票:0回答:1

您好,我有接受POST请求的控制器。

请求正文可以为空或正文为空字段:即或{}

@RestController
public class UserController {
    @Autowired
    private UserService UserService;
    @RequestMapping(value = "/tree", method = POST,consumes = MediaType.APPLICATION_JSON_VALUE)
    public List<ResponseUser> controller(@RequestBody(required=false) UserDataRequest request) {
        return UserService.send(request);
    }
}

我的服务定义如下:

  1. 检查主体是否为空,即为空
  2. 要一一检查该字段是否为空
  3. 如果字段为空,则再次执行步骤1
@Service
public class UserService {

    @Autowired
    private RestTemplate restTemplate;

    private ResponseEntity<List<ResponseUser>> responseEntity;

    public List<ResponseUser> send(UserDataRequest data){


        //empty body == null
    if(data == null ) {
           // return list1 of type ResponseUser
        }
    else{

       //Check for the fields are present are not
        Optional<String> id = Optional.ofNullable(data.getid());
        Optional<String> search = Optional.ofNullable(data.getsearch());

        //if id is present 
        if (id.isPresent()) {
            // return list2 of type ResponseUser

        }

        //if search is present 
        else if(search.isPresent()){
        // return list3 of type ResponseUser

            }

        else {
        // return list1 of type ResponseUser
        }
    }
    return responseEntity.getBody();
    }
}

我想知道如何不再重复相同的事情?有什么有效的方法吗?

java json spring-boot request http-post
1个回答
0
投票

将验证批注添加到您的Pojo类中

public class UserDataRequest {
@NotNull
private String id;

@NotNull
private String search;
}

更新您的发布方法以使用此验证

 public List<ResponseUser> send(@Valid UserDataRequest data){}
© www.soinside.com 2019 - 2024. All rights reserved.