简体   繁体   中英

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

Is it possible to define same path for two classes?

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

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

It is possible. See the JAX-RS Spec 3.7.2 Request Matching . In layman's terms, the spec states that all matching root resource classes are put into a set, then all the matching methods from those classes are put into a set. Then sorted. So if the resource class level @Path s are the same, they will both be put into the set for further processing

You can easily test this out, as I have done 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);
    }
}

Isn't possible, you have that to separate with the methods.

Example:

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

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

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

I hope this help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM