I have a RestController with a few endpoints and some of them receive a lot of request params. Could you give me a few tips how to improve it? It doesn't look good.
@GetMapping("/rest/players")
public ResponseEntity<List<Player>> getPlayersAccordingToParams(@RequestParam(required = false) String name,
@RequestParam(required = false) String title,
@RequestParam(required = false) Race race,
@RequestParam(required = false) Profession profession,
@RequestParam(required = false) Long after,
@RequestParam(required = false) Long before,
@RequestParam(required = false) Boolean banned,
@RequestParam(required = false) Integer minExperience,
@RequestParam(required = false) Integer maxExperience,
@RequestParam(required = false) Integer minLevel,
@RequestParam(required = false) Integer maxLevel,
@RequestParam(required = false) Integer pageSize,
@RequestParam(required = false) Integer pageNumber,
@RequestParam(required = false) PlayerOrder order) {
Pageable pageable = PageableCreator.createPageableFromParams(pageSize, pageNumber, order);
List<Player> players = playerService.findPlayersByRequestedParam(name, title, race,
profession, after,
before, banned, minExperience, maxExperience,
minLevel, maxLevel, pageable);
return new ResponseEntity<>(players, HttpStatus.OK);
}
@GetMapping("/rest/players/count")
public ResponseEntity<Integer> getPlayersCount(@RequestParam(required = false) String name,
@RequestParam(required = false) String title,
@RequestParam(required = false) Race race,
@RequestParam(required = false) Profession profession,
@RequestParam(required = false) Long after,
@RequestParam(required = false) Long before,
@RequestParam(required = false) Boolean banned,
@RequestParam(required = false) Integer minExperience,
@RequestParam(required = false) Integer maxExperience,
@RequestParam(required = false) Integer minLevel,
@RequestParam(required = false) Integer maxLevel) {
int count = playerService.countPlayersByRequestedParam(name, title, race,
profession, after,
before, banned, minExperience, maxExperience,
minLevel, maxLevel);
return new ResponseEntity<>(count, HttpStatus.OK);
CodePudding user response:
The best apporoach is to use the POJO class to map the request params to their respective attribute in the POJO and use the same in your code.
CodePudding user response:
You can use Map object as @RequestParam to accept all requestParams
For example:
@GetMapping(value = "/rest/players")
public ResponseEntity<List<Player>> getPlayersAccordingToParams(@RequestParam Map<String,String> requestParams){
String name=requestParams.get("name");
String title=requestParams.get("title");
.
.
.
.
}