Register a Servlet with the Http Service
Purpose
Register a simple service with the OSGi Http Service.
Prerequisites
- Servlet API bundles
- Http Service
- Declarative Services
- osgi interfaces, provides all service interfaces for the OSGi specifications.
Instructions
The Http Service provides a method registerServlet that must be given an alias (starting with /) under which the servlet is visible on the website, a servlet instance, configuration parameters (may be null) , and a Http Context instance. If the latter is null, a default context is used.
The following example makes a component that is depends on the Http Service. The Declarative Runtime calls the bind method setHttp when a new Http Service is present. If this happens, we just register a simple servlet that prints Hello World.
Source: aQute/registerservlet/RegisterServletComponent package aQute.registerservlet; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import org.osgi.service.http.*; public class RegisterServletComponent { public void setHttp(HttpService http) throws ServletException, NamespaceException { http.registerServlet("/hello", new RegisterServlet(), null, null); } } class RegisterServlet extends HttpServlet { public void doGet(HttpServletRequest rq, HttpServletResponse rsp) throws IOException { PrintWriter pw = rsp.getWriter(); pw.println("Hello World"); rsp.setContentType("text/plain"); } }
The Bnd file is as follows:
Bnd file: aQute.registerservlet.bnd Export-Package: aQute.registerservlet Service-Component: aQute.registerservlet.RegisterServletComponent; \
http=org.osgi.service.http.HttpService
Links
- The specification discusses declarative services in chapter 112 of the OSGi Compendium.
- Declarative Services Javadoc
- Http Service Javadoc
- aQute.registerservlet.jar
- For simplicity, the servlet code was contained in the component. Normaly they are in separate files.



