如何向Sling Model Exporter传递查询参数过滤导出JSON内容
Sling Model Exporter传递请求参数实现过滤的方案
结论
可以直接通过Sling Model Exporter实现该需求,无需额外编写Sling Servlet。
具体实现步骤
- 第一步:调整Sling Model的适配类,增加
SlingHttpServletRequest作为可适配源,同时注入需要的请求参数
示例代码如下:
import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.resource.Resource; import org.apache.sling.models.annotations.DefaultInjectionStrategy; import org.apache.sling.models.annotations.Model; import org.apache.sling.models.annotations.injectorspecific.Children; import org.apache.sling.models.annotations.injectorspecific.Inject; import org.apache.sling.models.annotations.injectorspecific.Named; import org.apache.sling.models.annotations.Exporter; import org.apache.sling.models.annotations.ExporterConstants; import com.fasterxml.jackson.annotation.JsonGetter; import org.apache.commons.lang3.StringUtils; import java.util.List; import java.util.stream.Collectors; @Model( adaptables = {Resource.class, SlingHttpServletRequest.class}, resourceType = "你的项目/组件/国家容器的resourceType", defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL ) @Exporter( name = ExporterConstants.SLING_MODEL_EXPORTER_NAME, extensions = ExporterConstants.SLING_MODEL_EXTENSION ) public class CountryContainerModel { // 直接注入请求中的stateName查询参数 @Inject @Named("stateName") private String stateName; // 注入容器下所有州子组件的Model @Children private List<StateModel> stateChildren; // 导出JSON时返回过滤后的结果,而非全量子组件 @JsonGetter("stateData") public List<StateModel> getFilteredStateData() { if (StringUtils.isBlank(stateName)) { // 未传查询参数时返回全部数据,可按需调整为返回空/报错 return stateChildren; } // 按参数过滤子组件数据 return stateChildren.stream() .filter(state -> stateName.equals(state.getStateName())) .collect(Collectors.toList()); } // 其他国家维度的导出字段按需添加 }
- 第二步:请求时直接在URL后拼接查询参数即可获取过滤后的结果,示例请求地址:
http://some.com/country/jcr:content/parent-component.model.json?stateName=California
注意事项
- 必须将
SlingHttpServletRequest加入Sling Model的adaptables配置,否则无法注入请求相关的参数 - 如果要支持多条件筛选,只需要按相同规则注入对应的查询参数,在
getFilteredStateData方法中扩展过滤逻辑即可 - 可根据业务需求调整无参数时的返回逻辑,比如返回参数缺失的错误提示,而非全部数据
内容的提问来源于stack exchange,提问作者Learner
相关产品推荐
相关产品推荐

