您好,我有接受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);
}
}
我的服务定义如下:
@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();
}
}
我想知道如何不再重复相同的事情?有什么有效的方法吗?
将验证批注添加到您的Pojo类中
public class UserDataRequest {
@NotNull
private String id;
@NotNull
private String search;
}
更新您的发布方法以使用此验证
public List<ResponseUser> send(@Valid UserDataRequest data){}