如何使用查询参数控制 Jersey 序列化

How to control Jersey serialization using query params

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

我正在使用 Jersey 2.x 和 Hibernate 4 来管理实体以及一些 Spring 安全性 etc.The 问题是 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);
            }
        }
    }


}

泽西岛有 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