我有两个吊索模型:
@Model(adaptables = {SlingHttpServletRequest.class, Resource.class}, defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL)
public class VideoGridItem {
@SlingObject
private Resource resource;
@SlingObject
private SlingHttpServletRequest slingHttpServletRequest;
@PostConstruct
public void initVideoGridItem() {
String[] selectors = slingHttpServletRequest.getRequestPathInfo().getSelectors();
insideGrid = selectors == null || selectors.length == 0 ? false : Arrays.stream(selectors).anyMatch("grid"::equals);
url = URLUtils.addHTMLIfPage(resource.getResourceResolver(), linkUrl);
}
}
和
@Model(adaptables = SlingHttpServletRequest.class, defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL)
public class VideoListing {
private List<String> videoResourcePaths;
@PostConstruct
final void init() {
}
}
我使用HTL从视频列表组件中调用VideoGridItem组件(技术上是引用模型的资源):
<sly data-sly-list.videoResourcePath="${model.videoResourcePaths}">
<sly data-sly-resource="${videoResourcePath @ wcmmode='disabled', addSelectors='grid'}" data-sly-unwrap="true"></sly>
</sly>
现在,当我调试代码时,在initVideoGridItem中,slingHttpServletRequest为空。公平地说,没有直接请求此资源,但是我仍然需要能够访问选择器“ grid”。有什么办法可以从VideoGridItem.resource中做到这一点?
答案 0 :(得分:1)
@org.apache.sling.models.annotations.injectorspecific.Self
和@SlingObject
字段中使用resource
批注而不是slingHttpServletRequest
。自注入器将注入可自适应对象本身(即Sling请求)以及可从同一对象(资源)自适应的对象。Resource.class
批注中的可适应类型列表中删除@Model
。这将防止您的模型类从Resource
对象改编,这将导致slingHttpServletRequest
字段为空,并且您的@PostConstruct
方法将抛出NullPointerException
。答案 1 :(得分:0)
对不起,我没有尽快回复,但是我发现自己的缺点并继续前进。问题是我正在通过从代码中其他位置的资源改编它来创建VideoGridItem,当然Sling无法注入请求。我现在正在考虑空请求,并且我的代码运行良好。感谢您的回答!