October 13, 2020
Estimated Post Reading Time ~

Getting Resource Resolver in Sling Model

For getting the node properties we need the resourceResolver. To get resource resolver we generally use SlingHttpServletRequest. But if we are using Resource.class and SlingHttpServletRequest in @Model annotation then we don’t get the other injected values from the dialog.

So following is the method through which we can use Resource.class and as well as get the resource resolver.

We just to need to add @Source(“sling-object”) while injecting resource Resolver.

Following is the implemented code and highlighted are the key points to keep in mind.

@Model(adaptables = { Resource.class }, defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL)

public class CheckoutModel extends AbstractComponentModel {

private static final Logger logger = LoggerFactory.getLogger(CheckoutModel.class);

/** The Constant serialVersionUID. */

private static final long serialVersionUID = -2053795867922610987L;
private String seoURL;

@Inject
@Source("sling-object")
private ResourceResolver resourceResolver;

public String getCartSeoUrl() {
return getSeoUrl(ApplicationConstants.CART_SEO_URL);
}

public String getLogoOnSeoUrl() {
return getSeoUrl(ApplicationConstants.LOGON_SEO_URL);
}

@JsonIgnore
public String getSeoUrl(String path) {
Node node = null;
Resource res = resourceResolver.getResource(path);
if (res != null) {
node = res.adaptTo(Node.class);
}

try {
if (node != null && node.hasProperty(ApplicationConstants.SEO_URL_KEY)) {
seoURL = node.getProperty(ApplicationConstants.SEO_URL_KEY).getValue().toString();
}

} catch (ValueFormatException e) {
logger.error("Inside Value Format", e);
} catch (PathNotFoundException e) {
logger.error("Inside Path NOt Found", e);
} catch (RepositoryException e) {
logger.error("Inside Repository Exception", e);
}

return seoURL;

}
}


By aem4beginner

No comments:

Post a Comment

If you have any doubts or questions, please let us know.