You can't have mutliple @Path
annotations on a single method. It causes a "duplicate annotation" syntax error.
However, there's a number of ways you can effectively map two paths to a method.
Regular expressions in @Path annotation
The @Path
annotation in JAX-RS accepts parameters, whose values can be restricted using regular expressions.
This annotation:
@Path("a/{parameter: path1|path2}")
would enable the method to be reached by requests for both /a/path1
and /a/path2
. If you need to work with subpaths, escape slashes: {a:path1\/subPath1|path2\/subPath2}
Serving responses with a redirection status code
Alternatively, you could set up a redirection. Here's a way to do it in Jersey (the reference implementation of JAX-RS), by defining another subresource. This is just an example, if you prefer a different way of handling redirections, feel free to use it.
@Path("basepath")
public class YourBaseResource {
//this gets injected after the class is instantiated by Jersey
@Context
UriInfo uriInfo;
@Path("a/b")
@GET
public Responce method1(){
return Response.ok("blah blah").build();
}
@Path("a/b/c")
@GET
public Response method2(){
UriBuilder addressBuilder = uriInfo.getBaseUriBuilder();
addressBuilder.path("a/b");
return Response.seeOther(addressBuilder.build()).build();
}
}
Using a servlet filter to rewrite URLs
If you're going to need such functionality often, I suggest intercepting the incoming requests using a servlet filter and rewriting the paths on the fly. This should help you keep all redirections in one place. Ideally, you could use a ready library. UrlRewriteFilter
can do the trick, as long as you're fine with a BSD license (check out their google code site for details)
Another option is to handle this with a proxy set up in front of your Java app. You can set up an Apache server to offer basic caching and rewrite rules without complicating your Java code.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…