在AEM 6.3中,可以使用Sling模型来获取页面属性。Sling模型是AEM中的一种Java类,用于将JCR节点映射到Java对象上。以下是在AEM 6.3中使用Sling模型获取页面属性的步骤:
@Model
注解来标识该类为Sling模型,并使用@Inject
注解来注入需要的依赖项。package com.example.models;
import javax.inject.Inject;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.models.annotations.DefaultInjectionStrategy;
import org.apache.sling.models.annotations.Model;
@Model(adaptables = Resource.class, defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL)
public class MyModel {
@Inject
private String pageTitle;
public String getPageTitle() {
return pageTitle;
}
}
pageTitle
,并设置其值为页面的标题。package com.example.servlets;
import javax.servlet.Servlet;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.servlets.HttpConstants;
import org.apache.sling.api.servlets.SlingSafeMethodsServlet;
import org.apache.sling.models.factory.ModelFactory;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
@Component(service = Servlet.class, property = { "sling.servlet.methods=" + HttpConstants.METHOD_GET,
"sling.servlet.paths=" + "/bin/my-servlet" })
public class MyServlet extends SlingSafeMethodsServlet {
@Reference
private ModelFactory modelFactory;
@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) {
Resource resource = request.getResource();
MyModel myModel = modelFactory.createModel(resource, MyModel.class);
String pageTitle = myModel.getPageTitle();
// 使用获取到的页面属性进行后续操作
}
}
在上述示例中,MyModel
类是一个Sling模型,它将pageTitle
属性注入到Java对象中。在MyServlet
中,通过modelFactory.createModel()
方法来创建MyModel
实例,并从中获取页面属性。
这是在AEM 6.3中使用Sling模型获取页面属性的基本步骤。关于AEM和Sling模型的更多详细信息,可以参考腾讯云的相关文档和产品介绍:
领取专属 10元无门槛券
手把手带您无忧上云