我正在寻找一种动态方法来控制使用查询参数从请求返回的响应对象。
我使用 Jersey 2.x 和 Hibernate 4 来管理实体,并使用一些 Spring 来实现安全性等。问题是 Jersey 没有序列化附加实体,而只是序列化基本实体。我目前正在使用com.fasterxml.jackson.datatype.hibernate4
。这给了我一些灵 active 来处理如何使用 JPA fetch=Eager 等加载子实体和父实体。但是我真的想让这个动态化。
我通过指定 ?with=<someentity>
尝试了简单的动态加载。指定要附加的实体。当获取实体时,我使用反射来调用某个实体的 getter,并且它成功附加了实体,但是当发送实体时,它没有序列化附加的实体。
这是我正在尝试做的一个 super 简单的例子。这实际上只是一个分割在一起的部分,但想法是存在的。问题是当我从服务器取回 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);
}
}
}
}
最佳答案
Jersey 有 Entity Data Filtering来处理这个用例。希望您使用的是较新版本的 Jersey,因为直到(2.14 :-) 和 2.16 之间的某个地方才支持 Jackson。懒得查什么时候了。我猜您正在使用 jersey-media-json-jackson
。如果您的版本引入了 jersey-entity-filtering
依赖项,您就会知道您的版本是否受支持。您无需添加任何其他内容。
您只需要配置三件事:
- 注册
SelectableEntityFilteringFeature
。 配置查询参数名称。
.property(SelectableEntityFilteringFeature.QUERY_PARAM_NAME, "with")
过滤功能有不同类型,但这里是section on query param filtering 。没有太多信息,因为没有太多信息可告诉。您真正需要知道的是如何配置,并且它按照您的预期工作,即 ?with=prop1,prop2,prop3
关于java - 如何使用查询参数控制 Jersey 序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34686030/