You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Sling解析JSP优先级:组件继承场景下的Sightly最优实现方案咨询

最优实现方案

咱们可以利用AEM的资源类型继承机制和脚本查找优先级来完美实现需求,具体步骤和原理如下:

1. 搭建Component B的目录结构

先在项目中给Component B创建如下目录结构,核心是保留要重写的other.jsp,同时新增Sightly主渲染脚本:

apps/your-project/components/component-b/
├── componentB.html  # Component B的主Sightly脚本
├── other.jsp        # 重写后的other.jsp,会自动覆盖Component A的同名文件
└── .content.xml     # 已配置sling:resourceSuperType=component-a,sling:resourceType=component-b

2. 在Sightly主脚本中复用Component A的main.jsp

因为Component B要求用Sightly编写,我们需要在componentB.html中通过Sightly的data-sly-resource指令引入Component A的main.jsp,这样既能保留Sightly的特性,又能复用已有JSP逻辑:

<!-- apps/your-project/components/component-b/componentB.html -->
<sly data-sly-resource="${resource @ resourceType='component-a'}"/>

如果main.jsp是Component A的默认主脚本,上面的写法就足够;如果main.jsp是带选择器的特殊脚本,可以明确指定选择器:

<sly data-sly-resource="${resource @ resourceType='component-a', selectors='main'}"/>

3. 自动触发重写的other.jsp

当Component A的main.jsp中通过<jsp:include>或<%@ include %>引入other.jsp时,AEM的脚本查找逻辑会优先从当前资源类型(Component B)中查找对应文件,找不到才会去父资源类型(Component A)中读取。所以只要你在Component B目录下放了自定义的other.jsp,就会自动覆盖原版本,不需要额外配置。

核心原理总结

AEM的脚本查找优先级是:

  • 优先匹配当前请求的资源类型(Component B)下的脚本
  • 若未找到,依次向上查找父资源类型(Component A)的脚本
    这种机制让我们只需要替换需要修改的部分(other.jsp),复用不需要改动的核心逻辑(main.jsp),同时满足Component B用Sightly编写的要求,是最符合AEM设计理念的实现方式。

内容的提问来源于stack exchange,提问作者Denisa Corbu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:41:50