Implementatie verkoopmodel
Hieronder wordt beschreven hoe u het Sling-model implementeert:
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);
}
}
- ModelAnnotatie: de
@Model
annotatie wijst deze klasse als het Verschuiven Model aan, aanpasbaar vanSlingHttpServletRequest
en het uitvoeren van deParameterizedModel
interface. - Attributen van het Verzoek: de
@RequestAttribute
annotatie injecteert parameters HTML in het model. - Methoden:
getValue()
voegt de parameters samen, enisReady()
controleert dat de parameters niet leeg zijn.
De interface ParameterizedModel
wordt als volgt gedefinieerd:
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();
}
Voorbeeld-uitvoer
Met de parameters "Hello"
en "World"
genereert het HTML-script de volgende uitvoer:
<p>
Hello World, from the parameterized Sling Model!
</p>
Dit toont aan hoe geparameterized het Verzamelen Modellen in AEM kunnen worden beïnvloed gebaseerd op inputparameters die via HTML worden verstrekt.
recommendation-more-help