Sling CMS 学习:bundles(五)

本文介绍如何使用Apache Sling创建CMS组件,包括配置Maven项目、实现模型类及资源适配,通过示例展示了如何获取页面信息及子页面列表。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一,创建Sling Bundle Project

pom.xml

<?xml version="1.0" encoding="ISO-8859-1"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one
  or more contributor license agreements.  See the NOTICE file
  distributed with this work for additional information
  regarding copyright ownership.  The ASF licenses this file
  to you under the Apache License, Version 2.0 (the
  "License"); you may not use this file except in compliance
  with the License.  You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing,
  software distributed under the License is distributed on an
  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  KIND, either express or implied.  See the License for the
  specific language governing permissions and limitations
  under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.quincy.sling</groupId>
    <artifactId>com.quincy.sling.core</artifactId>
    <packaging>bundle</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>com.quincy.sling.core</name>
    <description>com.quincy.sling - com.quincy.sling.core</description>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.felix</groupId>
                <artifactId>maven-scr-plugin</artifactId>
                <version>1.16.0</version>
                <executions>
                    <execution>
                        <id>generate-scr-descriptor</id>
                        <goals>
                            <goal>scr</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.felix</groupId>
                <artifactId>maven-bundle-plugin</artifactId>
                <extensions>true</extensions>
                <version>2.4.0</version>
                <configuration>
					<instructions>
						<Sling-Model-Packages>
							com.quincy.core.models
						</Sling-Model-Packages>
					</instructions>
				</configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>6</source>
                    <target>6</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.sling</groupId>
                <artifactId>maven-sling-plugin</artifactId>
                <version>2.1.0</version>
                <configuration>
                    <slingUrl>http://localhost:8080/system/console</slingUrl>
                    <user>admin</user>
                    <password>admin</password>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.osgi</groupId>
            <artifactId>org.osgi.compendium</artifactId>
            <version>4.2.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.osgi</groupId>
            <artifactId>org.osgi.core</artifactId>
            <version>4.2.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.jcr</groupId>
            <artifactId>jcr</artifactId>
            <version>2.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.sling</groupId>
            <artifactId>org.apache.sling.api</artifactId>
            <version>2.18.2</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.5.10</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.felix</groupId>
            <artifactId>org.apache.felix.scr.annotations</artifactId>
            <version>1.9.8</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
         <dependency>
            <groupId>org.apache.sling</groupId>
            <artifactId>org.apache.sling.models.api</artifactId>
            <version>1.2.2</version>
			<scope>provided</scope>
        </dependency>
        
        <dependency>
			<groupId>org.osgi</groupId>
			<artifactId>org.osgi.service.component.annotations</artifactId>
			<version>1.4.0</version>
			<scope>provided</scope>
		</dependency>
		<!-- <dependency>
			<groupId>org.apache.sling</groupId>
			<artifactId>org.apache.sling.cms.core</artifactId>
			<version>0.9.0</version>
		</dependency> -->
        
    </dependencies>
    <profiles>
        <profile>
            <id>autoInstallBundle</id>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.apache.sling</groupId>
                        <artifactId>maven-sling-plugin</artifactId>
                        <executions>
                            <execution>
                                <id>install-bundle</id>
                                <goals>
                                    <goal>install</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
</project>

发布bundle:mvn clean install -PautoInstallBundle

二,创建models

package com.quincy.core.models;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.models.annotations.Model;
import org.apache.sling.models.annotations.injectorspecific.ValueMapValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.quincy.core.utils.CMSUtils;

@Model(adaptables={Resource.class})
public class TestComponentResource {

	private static final Logger log = LoggerFactory.getLogger(TestComponentResource.class);
	
	private Resource resource;
	private String resourceName;
	private String resourcePath;
	
	private String pageName;
	private String pagePath;
	
	private List<Map<String, String>> childrenPage;
	
	public TestComponentResource(Resource resource){
	    this.resource = resource;
	}
	
	@PostConstruct
	public void init(){
		resourceName = resource.getName();
		resourcePath = resource.getPath();
		
		Resource pageRsrc = CMSUtils.findParentResourceofType(resource, "sling:Page");
		pageName = pageRsrc.getName();
		pagePath = pageRsrc.getPath();
		
		Iterable<Resource> children = pageRsrc.getChildren();
		childrenPage = new ArrayList<Map<String, String>>();
		for (Iterator<Resource> iter = children.iterator(); iter.hasNext();) {
			Resource item = iter.next();
			if ("sling:Page".equals(item.getValueMap().get("jcr:primaryType", String.class))) {
				Map<String, String> i = new HashMap<String, String>();
				i.put("pageName", item.getName());
				i.put("pagePath", item.getPath());
				childrenPage.add(i);
			}
		}
	}
		
	@ValueMapValue
	private String text;
	
	public String getText() {
		return text;
	}

	public Resource getResource() {
		return resource;
	}

	public void setResource(Resource resource) {
		this.resource = resource;
	}

	public void setText(String text) {
		this.text = text;
	}

	public String getResourceName() {
		return resourceName;
	}

	public void setResourceName(String resourceName) {
		this.resourceName = resourceName;
	}

	public String getResourcePath() {
		return resourcePath;
	}

	public void setResourcePath(String resourcePath) {
		this.resourcePath = resourcePath;
	}

	public String getPageName() {
		return pageName;
	}

	public void setPageName(String pageName) {
		this.pageName = pageName;
	}

	public String getPagePath() {
		return pagePath;
	}

	public void setPagePath(String pagePath) {
		this.pagePath = pagePath;
	}

	public List<Map<String, String>> getChildrenPage() {
		return childrenPage;
	}

	public void setChildrenPage(List<Map<String, String>> childrenPage) {
		this.childrenPage = childrenPage;
	}
	
}
package com.quincy.core.models;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.annotation.PostConstruct;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.models.annotations.Model;
import org.apache.sling.models.annotations.injectorspecific.ValueMapValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Model(adaptables={SlingHttpServletRequest.class})
public class TestComponentRequest {

	private static final Logger log = LoggerFactory.getLogger(TestComponentRequest.class);
	
	private SlingHttpServletRequest request;
	
	public TestComponentRequest(SlingHttpServletRequest request){
	    this.request = request;
	}
	
	@PostConstruct
	public void init(){
		//text = "test-text";
	}
	
	@ValueMapValue
	private String text;
	
	public String getText() {
		return text;
	}

	public SlingHttpServletRequest getRequest() {
		return request;
	}

	public void setRequest(SlingHttpServletRequest request) {
		this.request = request;
	}

	public void setText(String text) {
		this.text = text;
	}
		
}
<%@include file="/libs/sling-cms/global.jsp"%>
<c:set var="testComponentRequest" value="${sling:adaptTo(slingRequest, 'com.quincy.core.models.TestComponentRequest')}" scope="request"  />
	TestComponentRequest: ${testComponentRequest.text} <br/>
	
	<sling:adaptTo var="testComponentResource" adaptable="${resource}" adaptTo="com.quincy.core.models.TestComponentResource" />
	TestComponentResource-text: ${testComponentResource.text} <br/>
	TestComponentResource-resource: ${testComponentResource.resourceName}------${testComponentResource.resourcePath} <br/>
	TestComponentResource-page: ${testComponentResource.pageName}------${testComponentResource.pagePath} <br/>
	TestComponentResource-childrenPage: <br/>
	<c:forEach var="page" items="${testComponentResource.childrenPage}">
	   &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Item ${page.index} : ${page.pageName} --- ${page.pagePath} 
	</c:forEach>

三,CMSUtils

/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.sling.api.resource;

import java.util.Iterator;

import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;

import org.apache.sling.api.adapter.Adaptable;

import org.osgi.annotation.versioning.ProviderType;

/**
 * Resources are pieces of content on which Sling acts
 * <p>
 * The <code>Resource</code> is also an {@link Adaptable} to get adapters to
 * other types. A JCR based resource might support adapting to the JCR Node on
 * which the resource is based.
 * <p>
 * A <code>Resource</code> object is valid for as long as the
 * <code>ResourceResolver</code> that provided this instance is valid. The
 * same applies in general to all objects returned by this instance,
 * especially those returned by a call to {@link #adaptTo(Class)}.
 * <p>
 * All implementations must support returning a value map from
 * {@link #getValueMap()}, even if the map is empty.
 * <p>
 * Implementor's Note: It is recommended to not implement this interface
 * directly. Rather consider either extending from {@link AbstractResource} or
 * {@link ResourceWrapper}. This will make sure your implementation will not be
 * suffering from missing method problems should the Sling Resource API be
 * extended in the future.
 */
@ProviderType
public interface Resource extends Adaptable {

    /**
     * The special resource type for resource instances representing nonexisting
     * resources (value is "sling:nonexisting"). This resource type is used by
     * {@link ResourceResolver} instances to mark a resource which could not
     * actually be resolved.
     *
     * @see #getResourceType()
     * @see ResourceUtil#isNonExistingResource(Resource)
     * @see ResourceResolver#resolve(javax.servlet.http.HttpServletRequest,
     *      String)
     */
    String RESOURCE_TYPE_NON_EXISTING = "sling:nonexisting";

    /**
     * Returns the absolute path of this resource in the resource tree.
     * @return The resource path
     */
    @Nonnull String getPath();

    /**
     * Returns the name of this resource. The name of a resource is the last
     * segment of the {@link #getPath() path}.
     *
     * @return The resource name
     * @since 2.1 (Sling API Bundle 2.2.0)
     */
    @Nonnull String getName();

    /**
     * Returns the parent resource or <code>null</code> if this resource
     * represents the root of the resource tree.
     *
     * @return The parent resource or {@code null}.
     * @throws org.apache.sling.api.SlingException If an error occurs trying to
     *             get the resource object from the path.
     * @throws IllegalStateException if the resource resolver has already been
     *             closed}.
     * @since 2.1 (Sling API Bundle 2.1.0)
     * @see ResourceResolver#getParent(Resource)
     */
    @CheckForNull Resource getParent();

    /**
     * Returns an iterator of the direct children of this resource.
     * <p>
     * This method is a convenience and returns exactly the same resources as
     * calling <code>getResourceResolver().listChildren(resource)</code>.
     *
     * @return An iterator for child resources.
     * @throws org.apache.sling.api.SlingException If an error occurs trying to
     *             get the resource iterator.
     * @throws IllegalStateException if the resource resolver has already been
     *             closed}.
     * @since 2.1 (Sling API Bundle 2.1.0)
     * @see ResourceResolver#listChildren(Resource)
     */
    @Nonnull Iterator<Resource> listChildren();

    /**
     * Returns an iterable of the direct children of this resource.
     * <p>
     * This method is a convenience and returns exactly the same resources as
     * calling <code>getResourceResolver().getChildren(resource)</code>.
     *
     * @return An iterable for child resources
     * @throws org.apache.sling.api.SlingException If an error occurs trying to
     *             get the resource iterator.
     * @throws IllegalStateException if the resource resolver has already been
     *             closed}.
     * @since 2.2 (Sling API Bundle 2.2.0)
     * @see ResourceResolver#getChildren(Resource)
     */
    @Nonnull Iterable<Resource> getChildren();

    /**
     * Returns the child at the given relative path of this resource or
     * <code>null</code> if no such child exists.
     * <p>
     * This method is a convenience and returns exactly the same resources as
     * calling <code>getResourceResolver().getResource(resource, relPath)</code>.
     *
     * @param relPath relative path to the child resource
     * @return The child resource or {@code null}
     * @throws org.apache.sling.api.SlingException If an error occurs trying to
     *             get the resource object from the path.
     * @throws IllegalStateException if the resource resolver has already been
     *             closed}.
     * @since 2.1 (Sling API Bundle 2.1.0)
     * @see ResourceResolver#getResource(Resource, String)
     */
    @CheckForNull Resource getChild(@Nonnull String relPath);

    /**
     * The resource type is meant to point to rendering/processing scripts,
     * editing dialogs, etc. It is usually a path in the repository, where
     * scripts and other tools definitions are found, but the
     * {@link ResourceResolver} is free to set this to any suitable value such
     * as the primary node type of the JCR node from which the resource is
     * created.
     * <p>
     * If the resource instance represents a resource which is not actually
     * existing, this method returns {@link #RESOURCE_TYPE_NON_EXISTING}.
     * @return The resource type
     */
    @Nonnull String getResourceType();

    /**
     * Returns the super type of the resource if the resource defines its
     * own super type. Otherwise <code>null</code> is returned.
     * A resource might return a resource super type to overwrite the
     * resource type hierarchy.
     * If a client is interested in the effective resource super type
     * of a resource, it should call {@link ResourceResolver#getParentResourceType(Resource)}.
     * @return The super type of the resource or {@code null}.
     * @throws IllegalStateException if this resource resolver has already been
     *             {@link ResourceResolver#close() closed}.
     */
    @CheckForNull String getResourceSuperType();

    /**
     * Checks if the resource has any child resources.
     *
     * @return <code>true</code> if the resource has any child resources
     * @throws IllegalStateException if this resource resolver has already been
     *             {@link ResourceResolver#close() closed}.
     * @since 2.4.4 (Sling API Bundle 2.5.0)
     */
    boolean hasChildren();

    /**
     * Is just a shortcut for {@code getResourceResolver().isResourceType(this, resourceType)}.
     *
     * @param resourceType the resource type to check this resource against
     * @see ResourceResolver#isResourceType(Resource, String)
     * @since 2.1.0 (Sling API Bundle 2.1.0)
     * @return <code>true</code> if the resource type or any of the resource's
     *         super type(s) equals the given resource type, <code>false</code> otherwise;
     *         <code>false</code> can also be returned if <code>resourceType</code> is null
     */
    boolean isResourceType(String resourceType);

    /**
     * Returns the meta data of this resource. The concrete data contained in the
     * {@link ResourceMetadata} object returned is implementation specific
     * except for the {@link ResourceMetadata#RESOLUTION_PATH} property which is
     * required to be set to the part of the request URI used to resolve the
     * resource.
     *
     * @return The resource meta data
     * @see ResourceMetadata
     */
    @Nonnull ResourceMetadata getResourceMetadata();

    /**
     * Returns the {@link ResourceResolver} from which this resource has been
     * retrieved.
     * @return The resource resolver
     */
    @Nonnull ResourceResolver getResourceResolver();

    /**
     * Returns a value map for this resource.
     * The value map allows to read the properties of the resource.
     * @return A value map
     * @since 2.5 (Sling API Bundle 2.7.0)
     */
    @Nonnull ValueMap getValueMap();
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值