SlingModels: Can I inject the SlingHttpServletRequest when adapting from Resource?

℡╲_俬逩灬. 提交于 2019-12-24 06:20:34

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!