Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create a route that return list if there is no param and return a single object if there is id param

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

/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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading