【问题标题】:How to control Jersey serialization using query params如何使用查询参数控制 Jersey 序列化
【发布时间】:2016-01-08 21:04:56
【问题描述】:

我正在寻找一种动态方式来控制使用查询参数从请求返回的响应对象。

我使用 Jersey 2.x 和 Hibernate 4 来管理实体以及一些用于安全性的 Spring 洒水等。问题是 Jersey 没有序列化附加的实体,而只是序列化基本实体。我目前正在使用com.fasterxml.jackson.datatype.hibernate4。这给了我一些灵活性来处理如何使用 JPA fetch=Eager 等加载子实体和父实体。但是我真的想让这个动态。

我通过指定?with=<someentity> 来指定要附加的实体尝试了一个简单的动态加载。获取实体时,我使用反射调用某个实体的 getter,它成功地附加了实体,但是当将实体发送出去时,它没有序列化附加的实体。

这是我正在尝试做的一个超级简单的例子。这实际上只是一个分开的部分,但想法就在那里。问题是当我从服务器获取 Campaign 对象时,它没有序列化通过调用 loadEntity 附加的实体。

@Path("campaign")
public class CampaignResource {


    @GET
    @Path("{entity_id}")
    public Campaign find(@PathParam("entity_id") final Long id, @QueryParam("with") final String with) {
        T entity = repository.findOne(id);
        load(entity, with);
        return entity;
    }



    /**
     * This is used to attach entities that are requested via the api.
     * 
     * @param entity
     * @param with
     */
    @SuppressWarnings("unused")
    protected void loadWithEntities(T entity, final String with) {
        String[] withFields;
        if (with.contains(",")) {
            // Split the with clause into separate values
            withFields = with.split(",");
        } else {
            // Single with clause
            withFields = new String[] { with };
        }

        for (String field : withFields) {
            final String getterMethodName = getMethodGetterForField(field);
            Method method = null;
            try {
                method = entityClass.getMethod(getterMethodName);

                if (method != null) {
                    logger.info("Loading entity " + getterMethodName);
                    // Some odd reason we have to assign the variable so that it
                    // is attached.
                    final Object attached = method.invoke(entity);
                }
            } catch (Exception e) {
                logger.error("Unable to find method name %s ", getterMethodName, e);
            }
        }
    }


}

【问题讨论】:

    标签: java jersey jackson jersey-2.0


    【解决方案1】:

    Jersey 有 Entity Data Filtering 来处理这个用例。希望您使用的是更高版本的 Jersey,因为直到(介于 2.14 :-) 和 2.16 之间才支持 Jackson。懒得查什么时候。我猜你正在使用jersey-media-json-jackson。如果它引入 jersey-entity-filtering 依赖项,您将知道您的版本是否受支持。您无需添加任何其他内容。

    你只需要配置三件事:

    1. 注册SelectableEntityFilteringFeature
    2. 配置查询参数名称。

      .property(SelectableEntityFilteringFeature.QUERY_PARAM_NAME, "with")
      

    有不同类型的过滤功能,但这里是section on query param filtering。没有太多信息,因为没有太多信息可讲。您真正需要知道的是如何配置,它会按您的预期工作,即?with=prop1,prop2,prop3

    【讨论】:

    • 这看起来正是我想要的。太感谢了。我迫不及待想试一试。
    • 关于如何支持通配符的任何想法。我希望能够做类似的事情。 with=advertiser.*,agency.* 获取所有字段。我正在查看 ScopeResolver,但没有看到任何可以让我选择所有字段的内容。再次感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-28
    • 1970-01-01
    • 2014-09-27
    • 2015-12-05
    • 2014-12-12
    • 1970-01-01
    相关资源
    最近更新 更多