SEO JSON-LD cho AEM Page AEM
Note này gom toàn bộ quy trình để sinh structured data (JSON-LD) trong <head> của AEM page:
- Chuẩn bị page template + component chỗ để render schema.
- Thiết kế DTO theo Schema.org (kể cả object lồng nhau, mảng object).
- Sinh JSON-LD bằng Sling Model + OSGi Service đọc trực tiếp JCR.
- Render ra HTL với
context='unsafe'.
Stack: Java 11, AEM 6.5, Gson (provided bởi AEM), Lombok.
1. Kiến trúc tổng thể
customheaderlibs.html (HTL)
└─ Sling Model (mỏng — chỉ inject service, currentPage, assembles DTO)
└─ SchemaExtractor (OSGi Service — traverse JCR, extract nội dung)
└─ DTO Schema.org (POJO + @SerializedName)
└─ Gson (disableHtmlEscaping) → chuỗi JSON-LD
Điểm quyết định kiến trúc:
- Schema được render ở base page component (
mysite/components/page) trong customheaderlibs.html → mọi page type kế thừa đều tự động có JSON-LD, không cần override từng component con.
- JSON-LD được sinh động (on-the-fly) lúc request: Sling Model đọc properties lẻ (
jcr:title, cq:lastModified...) rồi lắp DTO, không lưu nguyên khối JSON trong JCR. Hiệu năng không phải vấn đề vì HTML đã được Dispatcher cache; Sling Model chỉ chạy lúc miss cache.
- Nếu business yêu cầu author nhập tay / hybrid (inherit – auto-fill – manual), xử lý ở mục 4.6.
2. Chuẩn bị: page template + component
Custom page template gồm 2 phần ở 2 module:
mysite/
├── ui.apps/ → Component Definition (code/markup)
└── ui.content/ → Template Definition (cấu hình, structure, policies)
Chuỗi phụ thuộc:
Template /conf/mysite/settings/wcm/templates/custom-page
└── sling:resourceType → apps/mysite/components/custom-page
└── sling:resourceSuperType → apps/mysite/components/page
└── sling:resourceSuperType → core/wcm/components/page/v3/page
2.1 Component definition (ui.apps)
File: ui.apps/.../apps/mysite/components/custom-page/.content.xml
<?xml version="1.0" encoding="UTF-8"?>
<jcr:root xmlns:sling="http://sling.apache.org/jcr/sling/1.0"
xmlns:cq="http://www.day.com/jcr/cq/1.0"
xmlns:jcr="http://www.jcp.org/jcr/1.0"
jcr:primaryType="cq:Component"
jcr:title="Custom Page"
sling:resourceSuperType="mysite/components/page"
componentGroup=".hidden"/>
sling:resourceSuperType="mysite/components/page" → kế thừa toàn bộ render logic của base page (header, footer, clientlibs, JSON-LD). Không cần viết lại body.html/head.html.
componentGroup=".hidden" → ẩn khỏi Component Browser.
Component con chỉ include base head trước rồi thêm cái riêng:
<sly data-sly-include="/apps/mysite/components/page/customheaderlibs.html"/>
<!--/* CSS/JS riêng cho template này nếu cần */-->
<sly data-sly-call="${clientlib.css @ categories='mysite.custom-page'}"/>
Không include base head → trang không load được clientlib (mysite.base) và ContextHub.
Không sinh JSON-LD ở component con — base page đã sinh rồi. Sinh thêm ở con → duplicate schema trên trang (lỗi đã từng gặp với một model cũ đã bị xoá).
2.3 Page dialog (thêm tab custom)
File: ui.apps/.../components/custom-page/_cq_dialog/.content.xml
<jcr:root xmlns:sling="http://sling.apache.org/jcr/sling/1.0"
xmlns:cq="http://www.day.com/jcr/cq/1.0"
xmlns:jcr="http://www.jcp.org/jcr/1.0"
xmlns:nt="http://www.jcp.org/jcr/nt/1.0"
jcr:primaryType="nt:unstructured"
jcr:title="Page"
sling:resourceType="cq/gui/components/authoring/dialog"
sling:resourceSuperType="core/wcm/components/page/v3/page/cq:dialog">
<content jcr:primaryType="nt:unstructured"
sling:resourceType="granite/ui/components/coral/foundation/container">
<items jcr:primaryType="nt:unstructured">
<tabs jcr:primaryType="nt:unstructured"
sling:resourceType="granite/ui/components/coral/foundation/tabs">
<items jcr:primaryType="nt:unstructured">
<custom jcr:primaryType="nt:unstructured" jcr:title="Custom Properties"
sling:resourceType="granite/ui/components/coral/foundation/fixedcolumns">
<items jcr:primaryType="nt:unstructured">
<column jcr:primaryType="nt:unstructured"
sling:resourceType="granite/ui/components/coral/foundation/container">
<items jcr:primaryType="nt:unstructured">
<authorName jcr:primaryType="nt:unstructured"
jcr:title="Author Name"
sling:resourceType="granite/ui/components/coral/foundation/form/textfield"
name="./authorName"/>
<authorUrl jcr:primaryType="nt:unstructured"
jcr:title="Author URL"
sling:resourceType="granite/ui/components/coral/foundation/form/pathfield"
name="./authorUrl"/>
</items>
</column>
</items>
</custom>
</items>
</tabs>
</items>
</content>
</jcr:root>
sling:resourceSuperType="core/wcm/components/page/v3/page/cq:dialog" → kế thừa toàn bộ dialog gốc (Basic, SEO, Social Media...), tab mới được merge vào.
name="./authorName" → property authorName trên jcr:content của page — chính là nguồn dữ liệu cho schema.
2.4 Template definition (ui.content)
File: ui.content/.../conf/mysite/settings/wcm/templates/custom-page/.content.xml
<jcr:root xmlns:cq="http://www.day.com/jcr/cq/1.0"
xmlns:jcr="http://www.jcp.org/jcr/1.0"
jcr:primaryType="cq:Template">
<jcr:content
cq:templateType="/conf/mysite/settings/wcm/template-types/page"
jcr:primaryType="cq:PageContent"
jcr:title="Custom Page Template"
jcr:description="Page template with SEO JSON-LD schema"
status="enabled"/>
</jcr:root>
cq:templateType → template type nền.
status="enabled" → dùng được trong wizard "Create Page".
2.5 Structure (bố cục cố định) và initial
File: .../templates/custom-page/structure/.content.xml
<jcr:root xmlns:sling="http://sling.apache.org/jcr/sling/1.0"
xmlns:cq="http://www.day.com/jcr/cq/1.0"
xmlns:jcr="http://www.jcp.org/jcr/1.0"
xmlns:nt="http://www.jcp.org/jcr/nt/1.0"
jcr:primaryType="cq:Page">
<jcr:content
cq:template="/conf/mysite/settings/wcm/templates/custom-page"
jcr:primaryType="cq:PageContent"
sling:resourceType="mysite/components/custom-page">
<root jcr:primaryType="nt:unstructured"
sling:resourceType="mysite/components/container" layout="responsiveGrid">
<experiencefragment-header jcr:primaryType="nt:unstructured"
sling:resourceType="mysite/components/experiencefragment"
fragmentVariationPath="/content/experience-fragments/mysite/language-masters/en/site/header/master"/>
<container jcr:primaryType="nt:unstructured"
sling:resourceType="mysite/components/container" layout="responsiveGrid">
<title jcr:primaryType="nt:unstructured"
sling:resourceType="mysite/components/title" editable="{Boolean}true"/>
<container jcr:primaryType="nt:unstructured"
sling:resourceType="mysite/components/container"
editable="{Boolean}true" layout="responsiveGrid"/>
</container>
<experiencefragment-footer jcr:primaryType="nt:unstructured"
sling:resourceType="mysite/components/experiencefragment"
fragmentVariationPath="/content/experience-fragments/mysite/language-masters/en/site/footer/master"/>
</root>
<cq:responsive jcr:primaryType="nt:unstructured">
<breakpoints jcr:primaryType="nt:unstructured">
<phone jcr:primaryType="nt:unstructured" title="Smaller Screen" width="{Long}768"/>
<tablet jcr:primaryType="nt:unstructured" title="Tablet" width="{Long}1200"/>
</breakpoints>
</cq:responsive>
</jcr:content>
</jcr:root>
- Component không có
editable="{Boolean}true" → Template Author không xoá được, Content Author không sửa được (header/footer XF).
initial/.content.xml là nội dung copy vào page mới (không chứa header/footer, đã kế thừa từ structure).
policies/.content.xml ánh xạ component → policy; hierarchy của mapping phải khớp hierarchy của structure. Policy definition nằm ở /conf/mysite/settings/wcm/policies/.content.xml — khi thêm component mới có policy riêng, thêm policy node trước rồi mới tham chiếu.
- Page clientlibs (
mysite.dependencies, mysite.site) được load qua policy của page component; clientlib-base (mysite.base) được load trong customheaderlibs.html.
2.6 Thứ tự triển khai
ui.apps: component (.content.xml, customheaderlibs.html, _cq_dialog)
ui.content: policy mới (nếu cần) trong policies/.content.xml
ui.content: template (.content.xml, structure/, initial/, policies/)
core: Sling Model/Service cho JSON-LD
- Deploy và kiểm tra
3. Thiết kế DTO theo Schema.org
JSON mục tiêu — chú ý độ sâu: publisher.logo là tầng thứ ba:
{
"@context": "https://schema.org",
"@type": "NewsArticle",
"inLanguage": "en-GB",
"mainEntityOfPage": { "@type": "WebPage", "@id": "https://example.com/blog/post.html" },
"headline": "headline title",
"description": "description",
"image": "https://example.com/image.jpg",
"author": { "@type": "Organization", "name": "Author Name", "url": "https://example.com" },
"publisher": {
"@type": "Organization",
"name": "Publisher Name",
"logo": { "@type": "ImageObject", "url": "https://example.com/logo.png" }
},
"datePublished": "2025-10-15T10:00:00+00:00",
"dateModified": "2025-10-15T10:00:00+00:00",
"articleBody": "article body"
}
3.1 Quy tắc map JSON → Java
- Mỗi object con
{ } → một class Java riêng.
- Key có
@ (@type, @id, @context) map bằng @SerializedName vì không hợp lệ làm tên field.
- Object dùng lại ở nhiều nơi (
Organization, ImageObject) → class top-level để tái sử dụng; dùng đúng một lần → static nested class cho gọn.
- Gson bỏ qua field null mặc định → field optional (như
logo của author) chỉ cần để null.
package com.mysite.core.models.seo;
import com.google.gson.annotations.SerializedName;
/** mainEntityOfPage */
public class WebPage {
@SerializedName("@type") private final String type = "WebPage";
@SerializedName("@id") private String id;
public WebPage(String id) { this.id = id; }
public void setId(String v) { this.id = v; }
}
/** dùng cho cả author và publisher */
public class Organization {
@SerializedName("@type") private final String type = "Organization";
private String name;
private String url;
private ImageObject logo; // optional, null → Gson bỏ qua
public void setName(String v) { this.name = v; }
public void setUrl(String v) { this.url = v; }
public void setLogo(ImageObject v) { this.logo = v; }
}
/** publisher.logo */
public class ImageObject {
@SerializedName("@type") private final String type = "ImageObject";
private String url;
public ImageObject(String url) { this.url = url; }
public void setUrl(String v) { this.url = v; }
}
public class NewsArticleSchema {
@SerializedName("@context") private final String context = "https://schema.org";
@SerializedName("@type") private final String type = "NewsArticle";
private String inLanguage;
private WebPage mainEntityOfPage;
private String headline;
private String description;
private String image;
private Organization author;
private Organization publisher;
private String datePublished;
private String dateModified;
private String articleBody;
// Getters/Setters cho toàn bộ field
public void setInLanguage(String v) { this.inLanguage = v; }
public void setMainEntityOfPage(WebPage v) { this.mainEntityOfPage = v; }
public void setHeadline(String v) { this.headline = v; }
public void setDescription(String v) { this.description = v; }
public void setImage(String v) { this.image = v; }
public void setAuthor(Organization v) { this.author = v; }
public void setPublisher(Organization v) { this.publisher = v; }
public void setDatePublished(String v) { this.datePublished = v; }
public void setDateModified(String v) { this.dateModified = v; }
public void setArticleBody(String v) { this.articleBody = v; }
}
3.2 Mảng object: BreadcrumbList
Schema dạng list dùng List<T>, gson tự serialize thành mảng JSON.
public class BreadcrumbListSchema {
@SerializedName("@context") private final String context = "https://schema.org";
@SerializedName("@type") private final String type = "BreadcrumbList";
private List<ListItem> itemListElement = new ArrayList<>();
public void addItem(ListItem item) { this.itemListElement.add(item); }
}
public class ListItem {
@SerializedName("@type") private final String type = "ListItem";
private int position;
private String name;
private String item; // URL tuyệt đối
public ListItem(int position, String name, String item) {
this.position = position;
this.name = name;
this.item = item;
}
}
Build bằng cách duyệt cây page cha từ currentPage lên tới site root:
BreadcrumbListSchema breadcrumb = new BreadcrumbListSchema();
List<Page> trail = new ArrayList<>();
Page p = currentPage;
while (p != null && p.getDepth() >= 3) { // "/" = depth 0, site root = depth 2
trail.add(0, p);
p = p.getParent();
}
int pos = 1;
for (Page page : trail) {
breadcrumb.addItem(new ListItem(pos++, page.getTitle(),
externalizer.publishLink(resourceResolver, page.getPath() + ".html")));
}
3.3 Mảng hai tầng: FAQPage
FAQPage lồng Question, mỗi Question lồng acceptedAnswer (Answer). Dữ liệu thường đến từ multifield trong dialog, đọc bằng @ChildResource.
public class FaqPageSchema {
@SerializedName("@context") private final String context = "https://schema.org";
@SerializedName("@type") private final String type = "FAQPage";
private List<Question> mainEntity = new ArrayList<>();
public void addQuestion(Question q) { this.mainEntity.add(q); }
}
public class Question {
@SerializedName("@type") private final String type = "Question";
private String name;
private Answer acceptedAnswer;
public Question(String name, String answerText) {
this.name = name;
this.acceptedAnswer = new Answer(answerText);
}
}
public class Answer {
@SerializedName("@type") private final String type = "Answer";
private String text;
public Answer(String text) { this.text = text; }
}
@ChildResource(name = "faqItems")
private List<Resource> faqItems;
// trong PostConstruct
FaqPageSchema faq = new FaqPageSchema();
if (faqItems != null) {
for (Resource item : faqItems) {
var vm = item.getValueMap();
faq.addQuestion(new Question(vm.get("question", ""), vm.get("answer", "")));
}
}
3.4 Nhiều schema trên một page
Một page có thể cần NewsArticle lẫn BreadcrumbList → mỗi schema một thẻ <script> riêng:
<sly data-sly-use.seo="com.mysite.core.models.schema.NewsArticleSeoModel"></sly>
<sly data-sly-test="${seo.jsonLdString}">
<script type="application/ld+json">${seo.jsonLdString @ context='unsafe'}</script>
</sly>
<sly data-sly-test="${seo.breadcrumbJson}">
<script type="application/ld+json">${seo.breadcrumbJson @ context='unsafe'}</script>
</sly>
Muốn gộp nhiều entity trong một script thì dùng @graph:
{
"@context": "https://schema.org",
"@graph": [
{ "@type": "NewsArticle", "headline": "..." },
{ "@type": "BreadcrumbList", "itemListElement": [] }
]
}
4. Sinh JSON-LD ở backend
4.1 OSGi Service — extract articleBody từ JCR
articleBody cần nội dung của tất cả text component trên trang, không phải một property duy nhất. Cách đúng: traverse cây JCR, đọc property text của các text component, strip HTML.
File: core/src/main/java/com/mysite/core/services/ArticleSchemaExtractor.java
package com.mysite.core.services;
import com.day.cq.wcm.api.Page;
/** Service traverse JCR content tree của page để thu thập nội dung cho JSON-LD. */
public interface ArticleSchemaExtractor {
String extractArticleBody(Page page);
}
File: core/src/main/java/com/mysite/core/services/impl/ArticleSchemaExtractorImpl.java
package com.mysite.core.services.impl;
import com.day.cq.wcm.api.Page;
import com.mysite.core.services.ArticleSchemaExtractor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ValueMap;
import org.osgi.service.component.annotations.Component;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
@Slf4j
@Component(service = ArticleSchemaExtractor.class)
public class ArticleSchemaExtractorImpl implements ArticleSchemaExtractor {
/** Resource types của các text component cần thu thập nội dung. */
private static final Set<String> TEXT_RESOURCE_TYPES = new HashSet<>(Arrays.asList(
"mysite/components/text",
"core/wcm/components/text/v2/text",
"core/wcm/components/text/v1/text"
));
@Override
public String extractArticleBody(Page page) {
if (page == null) {
return StringUtils.EMPTY;
}
Resource contentResource = page.getContentResource();
if (contentResource == null) {
log.warn("Không tìm thấy jcr:content cho page: {}", page.getPath());
return StringUtils.EMPTY;
}
StringBuilder bodyBuilder = new StringBuilder();
collectTextFromJcr(contentResource, bodyBuilder);
return bodyBuilder.toString().trim();
}
private void collectTextFromJcr(Resource resource, StringBuilder builder) {
ValueMap props = resource.getValueMap();
String resourceType = props.get("sling:resourceType", StringUtils.EMPTY);
if (TEXT_RESOURCE_TYPES.contains(resourceType)) {
String htmlText = props.get("text", StringUtils.EMPTY);
if (StringUtils.isNotBlank(htmlText)) {
String plainText = stripHtmlTags(htmlText);
if (StringUtils.isNotBlank(plainText)) {
builder.append(plainText).append(" ");
}
}
}
for (Resource child : resource.getChildren()) {
collectTextFromJcr(child, builder);
}
}
private String stripHtmlTags(String html) {
return html
.replaceAll("<[^>]*>", " ")
.replace(" ", " ")
.replace("&", "&")
.replace("<", "<")
.replace(">", ">")
.replace(""", "\"")
.replace("'", "'")
.replaceAll("\\s+", " ")
.trim();
}
}
Tại sao đọc JCR trực tiếp thay vì render HTML rồi parse:
4.2 package-info.java — bắt buộc
Mỗi Java package trong bundle core phải có package-info.java riêng với @Version. Thiếu → bnd không export package → HTL compiler không tìm thấy class → lỗi com.mysite.core.models.schema.ArticlePageModel cannot be resolved to a type.
File: core/src/main/java/com/mysite/core/models/schema/package-info.java
@Version("1.0")
package com.mysite.core.models.schema;
import org.osgi.annotation.versioning.Version;
Sub-package không kế thừa package-info.java từ parent: com.mysite.core.models được export không có nghĩa com.mysite.core.models.schema cũng được export.
4.3 Sling Model — lắp ráp toàn bộ schema
Model mỏng: inject service + currentPage + Externalizer, lắp DTO từ trong ra ngoài (tạo ImageObject trước → gắn vào publisher → gắn vào schema), serialize bằng Gson.
File: core/src/main/java/com/mysite/core/models/schema/NewsArticleSeoModel.java
package com.mysite.core.models.schema;
import com.day.cq.commons.Externalizer;
import com.day.cq.wcm.api.Page;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.mysite.core.models.seo.*;
import com.mysite.core.services.ArticleSchemaExtractor;
import org.apache.commons.lang3.StringUtils;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.models.annotations.DefaultInjectionStrategy;
import org.apache.sling.models.annotations.Model;
import org.apache.sling.models.annotations.injectorspecific.OSGiService;
import org.apache.sling.models.annotations.injectorspecific.ScriptVariable;
import org.apache.sling.models.annotations.injectorspecific.SlingObject;
import javax.annotation.PostConstruct;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
@Model(adaptables = SlingHttpServletRequest.class,
defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL)
public class NewsArticleSeoModel {
@ScriptVariable
private Page currentPage;
@SlingObject
private ResourceResolver resourceResolver;
@OSGiService
private Externalizer externalizer;
@OSGiService
private ArticleSchemaExtractor schemaExtractor;
private String jsonLdString;
@PostConstruct
protected void init() {
if (currentPage == null) {
return;
}
var props = currentPage.getProperties();
var schema = new NewsArticleSchema();
schema.setInLanguage(resolveLanguage());
schema.setHeadline(props.get("jcr:title", currentPage.getName()));
schema.setDescription(props.get("jcr:description", ""));
schema.setArticleBody(schemaExtractor != null ? schemaExtractor.extractArticleBody(currentPage) : "");
String pageUrl = toAbsoluteUrl(currentPage.getPath() + ".html");
schema.setMainEntityOfPage(new WebPage(pageUrl));
String imagePath = props.get("fileReference", String.class);
if (StringUtils.isNotBlank(imagePath)) {
schema.setImage(toAbsoluteUrl(imagePath));
}
Organization author = new Organization();
author.setName(props.get("authorName", "My Company"));
String siteRootPath = "/content/mysite/en"; // hoặc suy ra từ currentPage.getPath()
author.setUrl(toAbsoluteUrl(siteRootPath + ".html"));
schema.setAuthor(author);
Organization publisher = new Organization();
publisher.setName("My Company");
publisher.setLogo(new ImageObject(toAbsoluteUrl("/content/dam/mysite/logo.png")));
schema.setPublisher(publisher);
schema.setDatePublished(toIso8601(props.get("cq:lastReplicated", Calendar.class)));
schema.setDateModified(toIso8601(props.get("cq:lastModified", Calendar.class)));
Gson gson = new GsonBuilder().disableHtmlEscaping().create();
this.jsonLdString = gson.toJson(schema);
}
private String resolveLanguage() {
return currentPage.getLanguage(false) != null
? currentPage.getLanguage(false).toLanguageTag()
: "en-GB";
}
private String toAbsoluteUrl(String path) {
return externalizer.publishLink(resourceResolver, path);
}
private String toIso8601(Calendar cal) {
if (cal == null) {
return null;
}
ZonedDateTime zdt = cal.toInstant().atZone(ZoneOffset.UTC);
return zdt.format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssXXX"));
}
public String getJsonLdString() {
return jsonLdString;
}
}
Điểm quan trọng:
defaultInjectionStrategy = OPTIONAL → nếu service chưa active, model vẫn khởi tạo được (trả output rỗng) thay vì fail model.
- Luôn null-check
schemaExtractor trước khi gọi. NPE trong @PostConstruct làm HTL dừng render → mất toàn bộ <head> (kể cả CSS).
@ScriptVariable Page currentPage chỉ hoạt động với adaptables = SlingHttpServletRequest.class.
GsonBuilder().disableHtmlEscaping() bắt buộc nếu không sẽ có & bị thành \u0026.
4.4 Externalizer — URL tuyệt đối
Schema.org yêu cầu @id, image, logo.url, author.url là URL tuyệt đối. Không hardcode domain; dùng OSGi Externalizer để lấy host theo môi trường.
// SAI: hardcode domain, vô dụng khi đổi môi trường
schema.setImage("https://example.com" + imagePath);
// DUNG: Externalizer đọc config theo domain publish
schema.setImage(externalizer.publishLink(resourceResolver, imagePath));
Cấu hình tại /system/console/configMgr → Day CQ Link Externalizer, khai báo domain local, author, publish. publishLink dùng domain publish.
Tip
publishLink trả về path không có extension cho page → nối ".html" trước khi truyền vào. Với DAM asset thì giữ nguyên path vì đã có extension file.
4.5 ISO 8601 cho datePublished / dateModified
Google yêu cầu ngày đúng ISO 8601 kèm timezone offset. Property AEM lưu kiểu Calendar phải convert:
ZonedDateTime zdt = cal.toInstant().atZone(ZoneOffset.UTC);
String iso = zdt.format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssXXX"));
Pattern XXX cho ra +00:00. Nếu dùng giờ local thay vì UTC, đổi ZoneOffset.UTC thành ZoneId.of("Europe/London").
4.6 Hybrid: inherit / auto-fill / manual
Nếu requirement là author nhập trường seoText trên Page Properties, thỏa mãn 3 điều:
- Nhập
inherit → kế thừa JSON-LD từ page cha.
- Auto-fill: lần đầu mở dialog, trường được điền JSON chuẩn sinh từ model.
- Nhập tùy ý → dùng luôn giá trị đó.
Render-time logic trong model — ưu tiên thẳng, không sinh động nếu author đã có giá trị:
String seoText = props.get("seoText", String.class);
if (StringUtils.isNotBlank(seoText)) {
if ("inherit".equalsIgnoreCase(seoText.trim())) {
this.jsonLdString = resolveInherited(currentPage); // đi lên page cha, đệ quy nếu cha cũng inherit
} else {
this.jsonLdString = seoText; // manual inject — dùng nguyên giá trị
}
}
// rỗng → để null, HTL sẽ không render script
Chỉ sinh ra khi author mở edit & save → persist vào seoText sau dialog, kết hợp Clientlib JavaScript + một Sling Servlet:
- Servlet GET nhận path → chạy logic sinh JSON như mô tả ở mục 4.3 → trả string JSON.
- Clientlib category
cq.authoring.dialog lắng nghe foundation-contentloaded: nếu textarea seoText đang trống và page thuộc loại schema được hỗ trợ (check qua template path/resourceType) → gọi AJAX GET tới servlet → điền kết quả vào textarea.
- Author luôn thấy chính xác cái gì sắp được lưu; nhấn "Save & Close" thì JSON được persist vào
seoText.
5. Render trong HTL
customheaderlibs.html của base page component (mysite/components/page):
<sly data-sly-use.clientlib="core/wcm/components/commons/v1/templates/clientlib.html">
<sly data-sly-call="${clientlib.css @ categories='mysite.base'}"/>
</sly>
<sly data-sly-resource="${'contexthub' @ resourceType='granite/contexthub/components/contexthub'}"/>
<sly data-sly-use.pageModel="com.mysite.core.models.schema.NewsArticleSeoModel">
<script type="application/ld+json"
data-sly-test="${pageModel.jsonLdString}">
${pageModel.jsonLdString @ context='unsafe'}
</script>
</sly>
data-sly-test → chỉ render <script> khi có output, không để tag rỗng.
context='unsafe' → HTL không escape JSON (dấu quoting sẽ vỡ nếu bị escape). Chỉ an toàn khi chuỗi được serialize từ object (Gson tự escape control characters). Nếu in chuỗi author nhập tay (seoText/customJsonLd), phải validate parse JSON trước (thử parse để kiểm tra hợp lệ) — không validate thì author có thể chèn </script> phá vỡ head.
- Đặt block schema sau clientlib CSS, và null-check trong
PostConstruct: model lỗi thì HTL vẫn render phần trước, ít nhất CSS không mất.
- Nếu component con override
customheaderlibs.html: data-sly-include base trước rồi thêm cái riêng, và không sinh schema ở con.
6. Build, deploy, kiểm tra
# Build core bundle
mvn clean install -pl core -PautoInstallBundle
# Build ui.apps
mvn clean install -pl ui.apps -PautoInstallPackage "-Dskip.installnodenpm=true" "-Dskip.npm=true"
# full build
mvn clean install -PautoInstallSinglePackage "-Dskip.installnodenpm=true" "-Dskip.npm=true"
PowerShell: các tham số -D phải được bọc trong "..." để tránh lỗi parse.
Kiểm tra:
- Mở trang ở Preview / View as Published.
- View Source → tìm
<script type="application/ld+json"> trong <head>:
{"@context":"https://schema.org","@type":"NewsArticle","headline":"...",...}
- Dán URL vào Rich Results Test và Schema Markup Validator. Validator báo rõ object con nào thiếu field bắt buộc (ví dụ
publisher.logo thiếu url).
- JSON-LD có thể không hiện ở Edit mode — AEM editor wrap resource khác, đó là behavior chuẩn; chỉ cần hiện ở Preview/Publish.
7. Lỗi thường gặp
8. Cấu trúc file đầy đủ
mysite/
├── ui.apps/src/main/content/jcr_root/apps/mysite/
│ ├── clientlibs/
│ │ └── clientlib-base/.content.xml ← categories="[mysite.base]"
│ └── components/
│ ├── page/
│ │ ├── .content.xml ← base page, resourceSuperType=core/wcm/...
│ │ ├── customheaderlibs.html ← clientlib base + ContextHub + JSON-LD schema
│ │ └── customfooterlibs.html ← clientlib base JS
│ └── custom-page/
│ ├── .content.xml ← resourceSuperType=mysite/components/page
│ ├── customheaderlibs.html ← include parent + phần riêng
│ └── _cq_dialog/.content.xml ← tab custom properties
│
├── ui.content/src/main/content/jcr_root/
│ └── conf/mysite/settings/wcm/
│ ├── template-types/page/.content.xml ← template type nền
│ ├── policies/.content.xml ← tất cả policies của site
│ └── templates/custom-page/
│ ├── .content.xml ← template metadata
│ ├── structure/.content.xml ← bố cục cố định (header XF, container, footer XF)
│ ├── initial/.content.xml ← nội dung khởi tạo
│ └── policies/.content.xml ← ánh xạ component → policy
│
└── core/src/main/java/com/mysite/core/
├── services/
│ ├── ArticleSchemaExtractor.java ← interface traverse JCR
│ └── impl/ArticleSchemaExtractorImpl.java ← implementation
└── models/
└── schema/
├── NewsArticleSeoModel.java ← Sling Model assembles DTO
├── package-info.java ← @Version bắt buộc
└── seo/ ← DTO: NewsArticleSchema, Organization, WebPage, ImageObject, BreadcrumbListSchema, FaqPageSchema...