gpt4 book ai didi

java - Jersey JAXRS 过滤器,在访问资源(Web 服务)之前提供未编码的实体

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:34:39 24 4
gpt4 key购买 nike

是否有一种优雅的方式(过滤器、 Hook )在 Jersey 中拦截未编码的实体(及其注释),然后再访问 Web 服务资源方法——那些用 @POST、@PUT 注释的方法。

我确实需要实体本身及其上的任何注释,然后使用 validator 注释的属性对该实体执行验证(看起来像 JSR 303,但我们不使用元数据注释整个 bean)。从资源的实现角度来看,我的目标是能够在资源方法中输入:

@Path("/people")
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public class PeopleService {
@POST
public Response createPerson(@CustomValidator("personValidator") Person person) throws URISyntaxException {
String uri = someService.createPerson(person);
return Response.created(new URI(uri)).entity(uri).build();
}
}

我开始编写自定义 MessageBodyReader,我设法让 JSON 完全工作,因为我只是委托(delegate)给 ObjectMapper 来反序列化 JSON。除此之外,我收到了参数的注释并且一切正常。但是,当我需要反序列化 XML 时,事情就崩溃了。我不知道如何获取 Jersey 会使用的原始反序列化器并委托(delegate)给它。我也觉得我在不必要地重写 Jersey 的部分,并且如果 jersey 在 MessageBodyReader 之后和实现调用允许自身扩展的 Web 资源服务之前有一个层,我宁愿停止使用 MessageBodyReader 作为一个 hacky 集成点,这样我可以向流中添加自定义行为。

最终,Jersey 是否有任何扩展点可以将未编码的实体和任何参数注释交给我,并允许我进行自定义处理?或者我是否必须自己弄清楚如何解码实体(使用 JAXBContext 或其他)?可能求助于 AOP?将 validator 注入(inject)资源类并放弃注释想法?

Jersey 版本:1.5

最佳答案

Ultimately, does Jersey have any extension points where it can hand me the unmarshalled entity and any of it's parameter anntotations and allow me to do custom handling?

是的,在 Jersey 1.x 中有一个 SPI,您可以在其中提供自己的方法调用程序。我从未实现过 SPI,但据我所知,它是在任何 MessageBodyReader 或过滤器之后调用的。看看ResourceMethodCustomInvokerDispatchProvider .来自 Javadocs:

An implementation (a service-provider) identifies itself by placing a provider-configuration file (if not already present), "com.sun.research.ws.rest.spi.invoker.ResourceMethodCustomInvokerDispatchProvider" in the resource directory META-INF/services, and including the fully qualified service-provider-class of the implementation in the file.

This interface is similar to ResourceMethodDispatchProvider, but allows to use a custom JavaMethodInvoker instance, which will be used to make the final Java method call.

如果您实现 ResourceMethodCustomInvokerDispatchProvider,您应该能够提供自己的 JavaMethodInvoker它将有权访问被调用的资源方法,包括它的所有参数和注释。

请注意,以上所有内容均适用于 Jersey 1.x。在 Jersey 2 中,ResourceMethodInvocationHandlerProvider 提供了类似的功能。

关于java - Jersey JAXRS 过滤器,在访问资源(Web 服务)之前提供未编码的实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13866613/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com