JAX-RS: Multiple paths

JavaJax Rs

Java Problem Overview


Is it possible to do something like that?

import javax.ws.rs.GET;
import javax.ws.rs.Path;

public class xxx
{
  @GET
  @Path(value = "path1")
  public Response m1()
  {
    ...
  }

  @GET
  @Path(value = "path2")
  public Response m1()
  {
    ...
  }
}

I'm using RESTEasy btw.

Java Solutions


Solution 1 - Java

Solution 2 - Java

yes you can do that although you will have to rename your methods so that their signature is different.

Update: Check Dieter Cailliau's answer, @Path("/{a:path1|path2}") is probably what you want...

public class BlahResource{
    @GET
    @Path("path1")
    public Response m1(){
        return Response.ok("blah").build();
    }

    @GET
    @Path("path2")
    public Response m2(){
        return this.m1();
}

you can check JSR-311's API and it's reference implementation named "jersey" there:

JSR311 API

Jersey

Solution 3 - Java

Some extra details about Path annotation...

As a previous responses state, regular expressions to be used with in the annotated path declaration mapping:

{" variable-name [ ":" regular-expression ] "} 

You can declare multiple paths, but there is also a path hierarchy that was not immediately obvious to me whereby the class annotated path prefixes the following method path annotations. One might write the following class for a concise multiple path option which could be useful for resource versioning perhaps.

@Path("/{a:v1|v2}")
@Produces("text/*")
public class BlahResource {

    @GET
    @Path("/blah")
    public Response m1() {
        return Response.ok("blah").build();
    }
}

Please note the fact that the class "BlahResource" has been declared with the path "/v1" or "/v2" making the resource accessible as:

$ curl localhost:8080/v1/blah
blah

and also

$ curl localhost:8080/v2/blah
blah

Solution 4 - Java

You could use sub resources to map two paths to the same resource:

public class MySubResource {
    @GET
    public Response m1() {
        return Response.ok("blah").build();
    }
}

@Path("/root")
public class MyRootResource {

    @Path("/path1")
    public MySubResource path1() {
        return new MySubResource();
    }

    @Path("/path2")
    public MySubResource path2() {
        return new MySubResource();
    }
 }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionterry207View Question on Stackoverflow
Solution 1 - JavaDieter CailliauView Answer on Stackoverflow
Solution 2 - JavafassegView Answer on Stackoverflow
Solution 3 - JavaOpentunedView Answer on Stackoverflow
Solution 4 - JavaBrill PappinView Answer on Stackoverflow