嗨,我有接受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
1.逐个检查字段是否为空
1.如果字段为空,则再次执行步骤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();
}
}
我想知道怎样才能不重复同样的事情?有什么有效的方法吗?
2条答案
按热度按时间yc0p9oo01#
向Pojo类添加验证注解
更新post方法以使用此验证
bq3bfh9z2#
回复@Pkumar
如果字段search、id为字符串值:
如果要检查请求是否为空,请回答一般问题: