Monthly Archives: April 2016

Example OSGi Web Application

In some of my OSGi talks I use the “Guessing Game” as the next great web application to conquer the world. It’s a web app that generates a random number and let’s you guess it, telling you whether you made it, are too high or too low.

You can find the latest sample codeĀ on github.

Some slides from the last OSGi Community event featuring this app:

Http Whiteboard – Simply Simple – Part I

Developing web components with OSGi can be very simple if you’re using the OSGi Http Whiteboard Specification (see OSGi Compendium Chapter 140). For example the Apache Felix Http Implementation supports this standard.

In this part of the tutorial we start pretty simple and just look at how to develop a servlet and register it as an active web component. In the next parts we’ll cover more details.

For the example we use Declarative Services (DS) to develop our components. This is the easiest and most elegant way of developing OSGi services and is a standard for OSGi component development (see OSGi Compendium Chapter 112). For a tutorial for Declarative Services seeĀ OSGi Components Tutorial.

Registering A Servlet with the Http Whiteboard

Let’s have a look at the typical Hello World Example. The below code registers a servlet which simply prints out Hello World if invoked.

@Component(service = Servlet.class, 
           scope=ServiceScope.PROTOTYPE,
           property= "osgi.http.whiteboard.servlet.pattern=/hello")
public class HelloWorldServlet extends javax.servlet.http.HttpServlet {

    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
        resp.getWriter().println("Hello World");
    }
}

With the @Component annotation the HelloWorldServlet is registered as a service of type Servlet with a prototype scope. Using the prototype scope for servlets is recommended and we’ll see in another part why. The more important property is osgi.http.whiteboard.servlet.pattern which defines the path under which the servlet is available, /hello in this case. Once deployed into an OSGi application which has support for the OSGi Http Whiteboard specification, this servlet is reachable using /hello from your browser.

And that’s all you have to do. So getting a servlet up and running comes down to using the @Component annotations and specifying the path. Everything else is taken care of and you can focus on implementing your business logic. Of course all the nice features of Declarative Services can be used within your servlet, like the @Reference annotation to use other services.