Reputation: 177
Hi I have the controller which accepts the POST request.
The request body can be empty or with body with null fields : i.e. or { }
@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);
}
}
I have service defined as follows :
@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();
}
}
I would like to know how to not repeat same thing again? Is there any efficient way?
Upvotes: 1
Views: 8656
Reputation: 919
Answer to @Pkumar
If fields: search, id are String values:
if (data == null || !StringUtils.hasText(data.getsearch())) {
// return list1 of type ResponseUser
}
if (!StringUtils.hasText(data.getid())) {
// return list2 of type ResponseUser
}
if (!StringUtils.hasText(data.getsearch())) {
// return list3 of type ResponseUser
}
Answer in general if you want to check request is empty:
if (request == null) {
// your logic here
}
Upvotes: 0
Reputation: 324
Add Validation annotation to your Pojo class
public class UserDataRequest {
@NotNull
private String id;
@NotNull
private String search;
}
update your post method to use this validation
public List<ResponseUser> send(@Valid UserDataRequest data){}
Upvotes: 2