【问题标题】:Intercept JAX-RS web service response to add JSON field拦截 JAX-RS Web 服务响应以添加 JSON 字段
【发布时间】:2016-03-08 05:24:27
【问题描述】:

我有一个返回响应对象的 JAX-RS Web 服务,如下所示(它在 WebLogic 12.2.1 中运行)。它将向客户端返回 JSON 响应。是否可以编写一个拦截器或过滤器,以便在返回 Web 服务调用时,它会在 JSON 响应中添加一个额外的字段?

@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("LogIn")
public Response logIn(@Context HttpServletRequest request, Parameters requestParameters) {...}

提前致谢。

【问题讨论】:

  • 您使用的是哪种 JAX-RS 实现?如果泽西岛那么你可以尝试实现ContainerResponseFilter。在覆盖filter() 时,它提供“ContainerResponseContext”对象,让您可以访问使用getEntity() 方法发送的响应。您可以修改此对象并将其设置回响应中。
  • 我正在使用泽西岛。我试过你的建议。有用。非常感谢!您可以将其发布为答案吗?
  • 我已将其更新为答案。如果有效,请接受它。

标签: json web-services jax-rs weblogic12c


【解决方案1】:

如果使用 Jersey,那么您可以尝试实现 ContainerResponseFilter

在覆盖filter() 时,它提供ContainerResponseContext 对象,使您可以访问使用getEntity() 方法发送的响应。

您可以修改此对象并将其设置回响应中。

public class ResponseInterceptor implements ContainerResponseFilter{

    @Override
    public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
            throws IOException {
        Object obj = responseContext.getEntity();
        // Modify the Response obj as per need
        responseContext.setEntity(obj);
    }
}

【讨论】:

    猜你喜欢
    • 2016-08-01
    • 1970-01-01
    • 2017-04-29
    • 2014-10-19
    • 2013-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    相关资源
    最近更新 更多