匹配任何路径的泽西资源 [英] Jersey resource that matches any path

查看:85
本文介绍了匹配任何路径的泽西资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 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 ServletModules 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

@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 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.

这篇关于匹配任何路径的泽西资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆