匹配任何路径的泽西资源 [英] Jersey resource that matches any path
问题描述
我正在使用 Jersey v1.x 和
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.
我正在考虑这样做,因为我的servlet由不同的组件组成(例如,位于/api
下的rest API和位于/
下的Web UI).
用Guice的话来说,这意味着我有几个ServletModule
,每个ServletModule
都设置了servlet的一部分:
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 ServletModule
s that each set up one part of the servlet:
- 在我的
ApiServletModule
中:serve("/api").with(GuiceContainer.class, conf)
- 在我的
WebUiServletModule
中:serve("/").with(GuiceContainer.class, conf)
- In my
ApiServletModule
:serve("/api").with(GuiceContainer.class, conf)
- In my
WebUiServletModule
:serve("/").with(GuiceContainer.class, conf)
在此设置中,我想从负责的每个子项目的代码库中定义Web应用程序每个部分(/api
或/
)的404响应主体,而不必重新实现Jersey
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
到目前为止,我已经尝试绑定与@Path("/")
,@Path("*")
和@Path("/*")
匹配的资源,但是当我请求/some/path/that/doesnt/exist
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
推荐答案
@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:
至少与Guice结合使用,这样的全部匹配"资源将拦截所有请求,而不管是否还有其他特定的资源可用.此外,您无法从资源内部修改HTTP响应状态代码.
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.
为此,Jersey具有ExceptionMapper
,可以通过添加@Provider
批注来实现和加载.一种特殊类型是ExceptionMapper<NotFoundException>
,当资源抛出NotFoundException
时将调用该类型.然后ExceptionMapper
可以决定要生成什么响应,包括状态码.
For this purpose, Jersey has ExceptionMapper
s 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.
这篇关于匹配任何路径的泽西资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!