Sling Model implementation
Here’s how you implement the Sling Model:
package com.example.core.models.impl;
import org.apache.commons.lang3.StringUtils;
import org.apache.sling.api.SlingHttpServletRequest;
import org.osgi.service.component.annotations.Model;
import org.osgi.service.component.annotations.RequestAttribute;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Model(
adaptables = { SlingHttpServletRequest.class },
adapters = { ParameterizedModel.class }
)
public class ParameterizedModelImpl implements ParameterizedModel {
private static final Logger log = LoggerFactory.getLogger(ParameterizedModelImpl.class);
// Use the @RequestAttribute annotation to inject the parameter set in the HTL.
// Note that the Sling Model field can be any type, but must match the type of object or value passed from HTL.
@RequestAttribute
private String myParameterOne;
// If the HTL parameter name is different from the Sling Model field name, use the name attribute to specify the HTL parameter name
@RequestAttribute(name = "myParameterTwo")
private String mySecondParameter;
// Do some work with the parameter values
@Override
public String getValue() {
return myParameterOne + " " + mySecondParameter + ", from the parameterized Sling Model!";
}
@Override
public boolean isReady() {
return StringUtils.isNotBlank(myParameterOne) && StringUtils.isNotBlank(mySecondParameter);
}
}
- Model Annotation: The
@Model
annotation designates this class as a Sling Model, adaptable fromSlingHttpServletRequest
and implementing theParameterizedModel
interface. - Request Attributes: The
@RequestAttribute
annotation injects HTL parameters into the model. - Methods:
getValue()
concatenates the parameters, andisReady()
checks that the parameters are not blank.
The ParameterizedModel
interface is defined as follows:
package com.example.core.models;
import org.osgi.annotation.versioning.ConsumerType;
@ConsumerType
public interface ParameterizedModel {
/**
* Get an example string value from the model. This value is the concatenation of the two parameters.
*
* @return the value of the model
*/
String getValue();
/**
* Check if the model is ready to be used.
*
* @return {@code true} if the model is ready, {@code false} otherwise
*/
boolean isReady();
}