Can I have the same path for two classes in Rest Api?

Is it possible to define the same path for two classes?

@Path("/resource")    
public class ResourceA{
..
..
}

@Path("/resource")
public class ResourceB(){
..
..
}

      

+3


source to share


2 answers


Impossible, you have this to split with methods.

Example:

@Path("/resource")    
public class Resource{

    @Path("/A")
    public void resourceA(){
      ...
    }
    @Path("/B")
    public void resourceB(){
      ...
    }
 ..
}

      



You can access the resource with url "/ resource / A" and resourceB with "/ resource / B".

I hope this help.

+1


source


Perhaps <... See JAX-RS Spec 3.7.2 Compliance Request . In layman terms, the specification states that all matching root resource classes are put into the collection, then all the matching methods from those classes are put into the collection. Then sorted. Therefore, if the resource class level is the @Path

same, they will both be put into a set for further processing.

You can easily test this as I did below (with Jersey Test Framework )



public class SamePathTest extends JerseyTest {

    @Test
    public void testSamePaths() {
        String xml = target("resource").request()
                .accept("application/xml").get(String.class);
        assertEquals("XML", xml);
        String json = target("resource").request()
                .accept("application/json").get(String.class);
        assertEquals("JSON", json);
    }

    @Path("resource")
    public static class XmlResource {
        @GET @Produces(MediaType.APPLICATION_XML)
        public String getXml() { return "XML"; }
    }

    @Path("resource")
    public static class JsonResource {
        @GET @Produces(MediaType.APPLICATION_JSON)
        public String getJson() { return "JSON"; }
    }

    @Override
    public Application configure() {
        return new ResourceConfig(XmlResource.class, JsonResource.class);
    }
}

      

+7


source







All Articles