要将Adobe AEM(Adobe Experience Manager)组件从HTL转换为HTML,可以使用以下代码示例:
${sample.title}
${sample.description}
// Sample.java
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.scripting.SlingScriptHelper;
import org.apache.sling.api.scripting.SlingBindings;
import org.apache.sling.scripting.sightly.pojo.Use;
public class Sample implements Use {
private String title;
private String description;
@Override
public void init(Bindings bindings) {
SlingBindings slingBindings = (SlingBindings) bindings;
SlingScriptHelper sling = slingBindings.getSling();
Resource resource = slingBindings.getResourceResolver().getResource(slingBindings.get("resource").toString());
// 获取组件属性
title = resource.getValueMap().get("title", String.class);
description = resource.getValueMap().get("description", String.class);
}
public String getTitle() {
return title;
}
public String getDescription() {
return description;
}
}
// SampleServlet.java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.apache.sling.api.scripting.SlingScriptHelper;
import org.apache.sling.scripting.sightly.pojo.Use;
public class SampleServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ResourceResolverFactory resourceResolverFactory = // 获取ResourceResolverFactory实例
ResourceResolver resourceResolver = // 使用ResourceResolverFactory获取ResourceResolver实例
SlingScriptHelper sling = // 获取SlingScriptHelper实例
// 获取HTL组件的Resource
Resource resource = resourceResolver.getResource("/apps/sample/sample.htl");
// 使用HTL组件和Java类将HTL转换为HTML
Use sample = sling.getService(Use.class);
sample.init(sling.getBindings());
String html = sling.include(resource.getPath(), "sample.html", true);
// 将HTML响应发送回客户端
response.setContentType("text/html");
response.getWriter().write(html);
}
}
在上述代码示例中,HTL组件(sample.htl)定义了一个包含标题和描述的简单div元素。Java类(Sample.java)用于获取组件的属性,并通过getter方法将它们提供给HTL组件。Java Servlet(SampleServlet.java)使用HTL组件和Java类将HTL转换为HTML,并将HTML响应发送回客户端。
请注意,在实际应用中,可能需要自定义和调整代码以适应特定的开发需求和AEM环境。