Implementing a RESTful web service with two parameters?

I am writing a RESTful Jersey web service. I have two web methods.

@Path("/persons")
public class PersonWS {
    private final static Logger logger = LoggerFactory.getLogger(PersonWS.class);

    @Autowired
    private PersonService personService;

    @GET
    @Path("/{id}")
    @Produces({MediaType.APPLICATION_XML})
    public Person fetchPerson(@PathParam("id") Integer id) {
        return personService.fetchPerson(id);
    }


}

Now I need to write another web method that takes two parameters: one is id, and one is name. It should be as shown below.

public Person fetchPerson(String id, String name){

}

How can I write a web method for the above method?

Thanks!

+4
source share
1 answer

You have two options: you can put them in the path, or you can use it as a query parameter.

i.e. you want it to look like this:

/{id}/{name}

or

/{id}?name={name}

For the first, just do:

@GET
@Path("/{id}/{name}")
@Produces({MediaType.APPLICATION_XML})
public Person fetchPerson(
          @PathParam("id") Integer id,
          @PathParam("name") String name) {
    return personService.fetchPerson(id);
}

For the second, just add the name as RequestParam. You can mix PathParamand RequestParams.

+16

All Articles