5

I am writing Jersey RESTful web services. I have below 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 one more web method which takes two parameters one is id and one more is name. It should be as below.

public Person fetchPerson(String id, String name){

}

How can i write a web method for above method?

Thanks!

user755806
  • 6,565
  • 27
  • 106
  • 153

1 Answers1

18

You have two choices - you can put them both in the path or you can have one as a query parameter.

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

/{id}/{name}

or

/{id}?name={name}

For the first one 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 one just add the name as a RequestParam. You can mix PathParams and RequestParams.

Tim B
  • 40,716
  • 16
  • 83
  • 128
  • Tim, in case of first case do i need to send a request as: http://somedomain.com/App/persons/2/3 ? Thanks! – user755806 Dec 23 '13 at 13:23
  • yeah..correct is there any way to pass the request as below? somedomain.com/App/persons/2_somename ? – user755806 Dec 23 '13 at 13:26
  • I've never tried it but I'd expect @Path("/{id}_{name}") to work. Really you are better off using a / though as it's what people will expect and because it will be escaped properly if there is a / in the name. I'm not sure off hand if _ will. – Tim B Dec 23 '13 at 13:32
  • If i use @Path("/{id}_{name}") then do i need to split it by _ and get the params? Thanks! – user755806 Dec 23 '13 at 13:38
  • No, the only change you make is to put an _ instead of the / in the @Path. No change to the code. – Tim B Dec 23 '13 at 13:40