Jersey resource that matches any path

3.5k views Asked by At

I am using Jersey v1.x and a Guice Servlet. What I'm trying to do is bind a Jersey Resource that matches any @Path, such that I can use Jersey to respond with a 404.

I'm looking to do this, since my servlet consists of different components (e.g. a rest API that lives under /api, and a web UI that lives under /. In Guice terms, that means I have several ServletModules that each set up one part of the servlet:

  • In my ApiServletModule: serve("/api").with(GuiceContainer.class, conf)
  • In my WebUiServletModule: serve("/").with(GuiceContainer.class, conf)

In this setup, I want to define what the 404 response body looks like for each part of the webapp (/api or /) from the codebase of each subproject responsible, without having to reimplement Jersey


So far I have tried to bind a resource that match @Path("/"), @Path("*") and @Path("/*"), but none of these seem to be picked up when I request /some/path/that/doesnt/exist

2

There are 2 answers

0
derabbink On BEST ANSWER

@peeskillet's answer is indeed correct, in the sense that it describes how you can create a Jersey resource that matches any path.
However, my goal of creating a resource that delivers 404 responses for whenever any other unmatched path is requested is not quite met by this answer:

At least in combination with Guice, will such a "match all"-resource intercept all requests, regardless of whether any more specific resources are available. Additionally, you cannot modify the HTTP response status code from within a resource.

For this purpose, Jersey has ExceptionMappers that can be implemented and loaded by adding the @Provider annotation. One particular type would be a ExceptionMapper<NotFoundException>, which is invoked when a Resource throws a NotFoundException. The ExceptionMapper can then decide what response to generate, including the status code.

0
Paul Samsotha On

You need to use the regex format of the path expression, i.e.

@Path("{any: .*}")

You could inject List<PathSegment> to look at all the segments if you need them.

public Response getSomething(@PathParam("any") List<PathSegment> segments)