I have defined a REST GET API which will take all the Request Parameters and returns the result based on the values of request parameters. Something like below:
@GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
public List<Student> findAll(@RequestParam Map<String, String> allRequestParams) {
if(allRequestParams.isEmpty()) {
return studentRepository.findAll();
} else {
return studentService.findWithFilter(allRequestParams); // This method will take care of using appropriate findBy method on the repository
}
}
The above code is using Spring way of retrieving all request parameters. I could instead inject HttpServletRequest and use getParametersMap() method to get all the request parameters. I have few questions:
- Is it better to use Spring way or use
getParameterMap()fromHttpServletRequest? - I was told in one of the code review that this kind of programming is anti-pattern? Can somebody shed some light on why it is considered as anti-pattern? And if it is an anti-pattern, then what is the best way to handle this kind of processing?
findAllshouldn't accept any filter. If you want such filterablefind, then add something likefindByIdorfindByName.Model, Authentication, Session, HttpServletRequestand others - and you can build your own providers if you like.