Search code examples
javaslingosgi-bundle

Configurable Java Servlet from OSGI


I'm trying to create a Java class that is configurable via the OSGi console. I've heard you can do this via SCR annotations but not entirely sure how. I've got the bulk of it but unsure what to get and post and how to reference it in the JSP. Here is what I have so far:

import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.sling.SlingServlet;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.servlets.SlingAllMethodsServlet;

import javax.servlet.ServletException;
import java.io.IOException;

@SlingServlet(
paths={"/somepath/"}
)
@Properties({
@Property(name="email.add", value="Email Info",propertyPrivate=false),
@Property(name="user.info",value="User Info", propertyPrivate=false)
})
public class WelcomeMessage extends SlingAllMethodsServlet
{
@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse                                 response) throws ServletException, IOException
{
    //Do something here
}

@Override
protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException
{
    //Do something here
}
}

Solution

  • To be able to process such annotations, you need to setup the Maven SCR Plugin (from Apache Felix). This plugin will process annotations and create metadata inside your resulting JAR file.

    @SlingServlet annotation is Apache Sling specific and will need certain Apache Sling bundles to be able to register the servlet. @SlingServlet annotations are also processed by the Maven SCR Plugin.

    Here is a sample on how to configure the SCR plugin in Maven.

    <build>
      <plugins>
        <plugin>
          <groupId>org.apache.felix</groupId>
          <artifactId>maven-scr-plugin</artifactId>
          <version>1.9.0</version>
          <executions>
            <execution>
              <id>generate-scr-scrdescriptor</id>
              <goals>
                <goal>scr</goal>
              </goals>
            </execution>
          </executions>
        </plugin>
      </plugins>
    </build>
    

    Also, to be able to create an OSGi bundle (Jar with OSGi metadata), you will need to setup the Maven Bundle Plugin.

    You can find a brief documentation on the Maven SCR Plugin here: http://felix.apache.org/documentation/subprojects/apache-felix-maven-scr-plugin.html.

    Maven Bundle plugin documentation is here: http://felix.apache.org/site/apache-felix-maven-bundle-plugin-bnd.html.

    But, the best way to understand this is by looking at examples in the Sling bundles here: https://github.com/apache/sling/tree/trunk/bundles.