Search code examples
javarestjerseyjax-rs

Can we have an empty base path?


Can we have an empty basepath for @Path annotation? ie. @Path("/")

I want to provide REST api http://servername/abc

@Path("")
public class YourResource {

  @Path("/abc")
  @GET
  public Responce method1(){
    return Response.ok("ok").build();
  }

}

When I do this, exception is thrown

javax.ws.rs.WebApplicationException at com.sun.jersey.server.impl.uri.rules.TerminatingRule.accept(TerminatingRule.java:66) at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108) at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)

UPDATE - I bind in my GuiceServletContextListener like below

bind(YourResource.class).in(Singleton.class);

serve("/abc").with(GuiceContainer.class);


Solution

  • Remove @Path("/") annotation completely from class

    and

    prefix slash (/) into the method level path annotation, like @Path("/abc")

    Please verify whether your URI is mapped to java method as below.

    While starting your server, you can see how the URI's mapped into the java methods, something like this in eclipse console...

    Mapped "{[/static/transit],methods=[],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.util.List<com.xxx.yyy.zzz.domain.Transit> com.xx.yy.zz.controller.abcDataController.getAllTransit()

    ==================================================================

    UPDATE:

    According to the java doc below, There are no difference between these 2 examples, both will work. Either you can use leading slash with both URIs or don't use any leading slash with both URIs, both are same.

    Paths are relative. For an annotated class the base URI is the application path, see ApplicationPath. For an annotated method the base URI is the effective URI of the containing class. For the purposes of absolutizing a path against the base URI , a leading '/' in a path is ignored and base URIs are treated as if they ended in '/'.

    @Path("message")
    
    public class MessageServices {
    
        @PUT
        @Path("sendsms")
        @Consumes(MediaType.APPLICATION_JSON)
        @Produces({MediaType.APPLICATION_JSON})
        public Response sendSms() {
            //....
        }
    
    }
    

    OR

    @Path("/message")
    public class MessageServices {
    
        @PUT
        @Path("/sendsms")
        @Consumes(MediaType.APPLICATION_JSON)
        @Produces({MediaType.APPLICATION_JSON})
        public Response sendSms() {
            //....
        }
    
    }