I have one route named /project, I want it this way if there is no param it will return list of projects, if there is id param in url it will return a single object
Currently this is what I have
@GetMapping(value={"/project", "/project/"})
public List<Project> getProjects() {
return projectService.getProjects();
}
@GetMapping("/project/{id}")
public Project getProject(@PathVariable int id) {
Optional<Project> project = projectService.getProject(id);
if (project.isPresent()) {
return (Project) project.get();
}
return null;
}
/project will return the list
/project/1 will return a single object
but what I wanted is
/project will return the list
/project?id=1 will return a single object
how to do that?
>Solution :
As mentioned in other answer. you need to use RequestParam. Additionally, in order to narrow down the mappings and deal with possible ambiguous handler mapping exceptions, you can use GetMapping.params to specify, which parameters need to be present to map to this particular handler. It’s alias for RequestMapping.params.
Same format for any environment: a sequence of "myParam=myValue" style expressions, with a request only mapped if each such parameter is found to have the given value. Expressions can be negated by using the "!=" operator, as in "myParam!=myValue". "myParam" style expressions are also supported, with such parameters having to be present in the request (allowed to have any value). Finally, "!myParam" style expressions indicate that the specified parameter is not supposed to be present in the request.
Example:
@GetMapping(value="/project", params = "!id")
public List<Project> getProjects() {
return projectService.getProjects();
}
@GetMapping(value = "/project", params = "id")
public Project getProject(@RequestParam int id) {
Optional<Project> project = projectService.getProject(id);
if (project.isPresent()) {
return (Project) project.get();
}
return null;
}