Snippets / RegisterServlet aQute - Software Consultancy
Search
*

Register a Servlet with the Http Service

Purpose

Register a simple service with the OSGi Http Service.

Prerequisites

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

Copyright 2006 aQute SARL, All Rights Reserved