What difference would it make if I write
@Model(adaptables=SlingHttpServlet.class)
?

- 20,533
- 11
- 60
- 86

- 13
- 1
- 5
1 Answers
These articles give good explanations:
- https://helpx.adobe.com/experience-manager/using/sling_model_adaptation.html
- https://sling.apache.org/documentation/bundles/models.html
The first link notes that
"There are use cases where you may need to get a Request object inside a Sling Model or you want to adapt your Sling Model using a SlingHttpServletRequest object (where you don’t want to create a resource object)."
The second link mentions
"Many Sling projects want to be able to create model objects - POJOs which are automatically mapped from Sling objects, typically resources, but also request objects. Sometimes these POJOs need OSGi services as well."
So whether you use one adaptable or the other (or both at once) depends on what you need in your model. In that example it creates a model that needs to read some values from the resource and others from the request, so the adaptable you would use depends on what values you need within your model. Here's the sample class in that first link that shows the "message" which needs data from the Resource (first and last name) and data from the Request (path):
package com.aem.core.models;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.models.annotations.Model;
import org.apache.sling.models.annotations.Via;
import org.apache.sling.models.annotations.injectorspecific.SlingObject;
import org.apache.sling.models.annotations.DefaultInjectionStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Model(adaptables = {SlingHttpServletRequest.class, Resource.class}, defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL)
public class AdaptationModel {
Logger logger = LoggerFactory.getLogger(this.getClass());
private String message;
@SlingObject
private SlingHttpServletRequest request;
@Inject @Via("resource")
private String firstName;
@Inject @Via("resource")
private String lastName;
@PostConstruct
protected void init() {
message = "Hello World\n";
if (request != null) {
this.message += "Request Path: "+request.getRequestPathInfo().getResourcePath()+"\n";
}
message += "First Name: "+ firstName +" \n";
message += "Last Name: "+ lastName + "\n";
logger.info("inside post construct");
}
public String getMessage() {
return message;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
}

- 8,374
- 5
- 37
- 60