54

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.

MauriceNino
  • 6,214
  • 1
  • 23
  • 60
terry207
  • 725
  • 3
  • 7
  • 9

4 Answers4

93
@Path("/{a:path1|path2}")

From resteasy docs: http://docs.jboss.org/resteasy/docs/1.0.2.GA/userguide/html_single/index.html#_Path_and_regular_expression_mappings

Dieter Cailliau
  • 931
  • 1
  • 6
  • 2
21

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

fasseg
  • 17,504
  • 8
  • 62
  • 73
  • It is also possible using resteasy? – terry207 Jan 25 '11 at 09:00
  • Actually there is no reason your answer is not a good one, in fact I would argue that it's better than most here, because those two methods can delegate to a single service responsible for doing the work. That makes your codes much more maintainable. – Brill Pappin Jan 31 '21 at 16:56
12

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
Opentuned
  • 1,477
  • 17
  • 21
0

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();
    }
 }
Brill Pappin
  • 4,692
  • 1
  • 36
  • 36