【问题标题】:How to check if the request body is empty or request body have empty fields in simple way?如何以简单的方式检查请求正文是否为空或请求正文是否有空字段?
【发布时间】:2019-10-01 15:41:01
【问题描述】:

您好,我有一个接受 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. 检查正文是否为空,即 null
  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】:

    为你的 Pojo 类添加验证注解

    public class UserDataRequest {
    @NotNull
    private String id;
    
    @NotNull
    private String search;
    }
    

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

     public List<ResponseUser> send(@Valid UserDataRequest data){}
    

    【讨论】:

    • 并不满足所有情况 Request 可以为空或 { }.. 另外 id 和 search 也可以为空。
    • @Pkumar 还有额外的 javax 验证比如 NotEmpty、NotBlank 可以使用
    猜你喜欢
    • 2020-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-05
    • 2019-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多