问题
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
?
回答1:
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.
回答2:
@Model(adaptables = { SlingHttpServletRequest.class, Resource.class }, defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL)
public class ImageModel {
@Self
private Resource resource;
@SlingObject
private ResourceResolver resourceResolver;
@SlingObject
SlingHttpServletRequest slingRequest;
}
来源:https://stackoverflow.com/questions/40908830/slingmodels-can-i-inject-the-slinghttpservletrequest-when-adapting-from-resourc