How do I create a Sling model using both a Resource and SlingHttpServletRequest? | Community
Skip to main content
jkpanera
Level 4
Jul 2, 2019 2:24 PM UTC
Solved

How do I create a Sling model using both a Resource and SlingHttpServletRequest?

Hey guys,

I need to initialize a sling model for component B from inside component A. I have access to a sling Resource object for component B and a SlingHttpServletRequest for component A.

So I can easily do:

ComponentB componentB = resourceForComponentB.adaptTo(ComponentB.class);

But the @PostConstruct initializer for ComponentB uses a SlingHttpServletRequest (up until now, it had only been adapted via request). How do I initialize the @SlingObject request so that the @PostConstruct for ComponentB will be able to execute (without a null pointer exception).

Thanks!

This post is no longer active and is closed to new replies. Need help? Start a new post to ask your question.
antoniom5495929
antoniom5495929Accepted solution
Level 7
Jul 3, 2019 12:19 PM UTC

Hi,

I think that you just need to define an adapter strategy like the following snippet:

@Model(adaptables = {SlingHttpServletRequest.class, Resource.class}, defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL)

Thanks,

Antonio

5 replies

joerghoh
Employee
Jul 3, 2019 7:42 PM UTC

If you want to adapt a SlingModel from both Request and Resource, make sure that you don't use data from the request, but only from the resource.

Because in both cases, the Resource is always present (in case of the request: request.getResource()), and just relying on that gives the model the most flexibility.

Jörg

Translate
jkpanera
jkpaneraAuthor
Level 4
Jul 3, 2019 3:58 PM UTC

I did that. I managed to get done what I needed by refactoring the initialization but I was wondering if there was a way to initialize using both the request and the resource. I guess there isn't.

Thanks!

Translate
antoniom5495929
antoniom5495929Accepted solution
Level 7
Jul 3, 2019 12:19 PM UTC

Hi,

I think that you just need to define an adapter strategy like the following snippet:

@Model(adaptables = {SlingHttpServletRequest.class, Resource.class}, defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL)

Thanks,

Antonio

Translate
joerghoh
Employee
Jul 2, 2019 7:56 PM UTC

You can't.

In the case you mentioned it's actually the programmer's fault to let the model declare that the model can be initialized by a resource only if a proper Request object is required to make the @PostConstruct work.

Translate
arunpatidar
New Participant
Jul 2, 2019 3:13 PM UTC