-1

I have two Sling Models:

@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);
  }
}

and

@Model(adaptables = SlingHttpServletRequest.class, defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL)
public class VideoListing {

  private List<String> videoResourcePaths;

  @PostConstruct
  final void init() {

  }

}

I call the VideoGridItem component (technically the resource which references the model) from the video-listing component using HTL:

  <sly data-sly-list.videoResourcePath="${model.videoResourcePaths}">
    <sly data-sly-resource="${videoResourcePath @ wcmmode='disabled', addSelectors='grid'}" data-sly-unwrap="true"></sly>
  </sly>

Now, when I debug the code, inside initVideoGridItem, slingHttpServletRequest is null. Fair enough, this resource isn't being directly requested, but I still need to be able to access the selector "grid". Is there a way I can do this from the VideoGridItem.resource?

Kramer
  • 927
  • 2
  • 13
  • 30

2 Answers2

1
  1. Use the @org.apache.sling.models.annotations.injectorspecific.Self annotation instead of @SlingObject for the resource and slingHttpServletRequest fields. The self injector will inject the adaptable object itself (i.e. the Sling request) as well as objects that are adaptable from the same (the resource).
  2. Assuming you always need the selector value for your component to function, you should remove Resource.class from the list of adaptable types in your @Model annotation. This will prevent your model class from being adapted from a Resource object, which will cause the slingHttpServletRequest field to be null and your @PostConstruct method will throw a NullPointerException.
0

Sorry I didn't reply sooner, but I found my defect and moved on. The issue was that I was creating a VideoGridItem by adapting it from a resource in another place in the code and of course Sling couldn't inject a request. I am now accounting for the null request and my code is working well. Thanks for your answer!

Kramer
  • 927
  • 2
  • 13
  • 30