SlingModels: Can I inject the SlingHttpServletRequ

2019-07-28 08:27发布

I am new to SlingModels and the annotations aren't very clear yet. I am currently trying to transform some basic foundation components from AEM 6.2 to using SlingModels instead.

For the image component the foundation JSP uses the SlingHttpServletRequest to set the ImageDoctype. So I tried the following:

@Model(adaptables = {Resource.class})
public class ImageModel {
    @SlingObject
    private SlingHttpServletRequest request;

    @SlingObject
    private Resource resource;
}

But with this the request is null. So I switched to using:

@Model(adaptables = {SlingHttpServletRequest.class})

Which works now for reuqest and resource

JSP Code:

<sling:adaptTo adaptable="${slingRequest}" adaptTo="models.ImageModel" var="m"/>

Is this the right way to do it or is there a way to adapt from the resource ans still be able to inject the request?

2条回答
姐就是有狂的资本
2楼-- · 2019-07-28 09:05

You can not do that, because resource is not SlingHttpServletRequest aware. If you need Request in your model make it adaptable from Request.

There was some library which allowed to do that. It used Filter to store current Request in ThreadLocal and then read it from it, but I would not recommend this approach. ThreadLocal is just another global.

查看更多
放荡不羁爱自由
3楼-- · 2019-07-28 09:19
@Model(adaptables =  { SlingHttpServletRequest.class, Resource.class }, defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL)
public class ImageModel {
    @Self 
    private Resource resource;

    @SlingObject
    private ResourceResolver resourceResolver;

    @SlingObject
    SlingHttpServletRequest slingRequest;
}
查看更多
登录 后发表回答