Embedding Jetty in OSGi: The Definitive Guide
…. well, not really definitive, since there’re a number of techniques/tools you can use to embed a servlet container in OSGi.
I found the approach I’m going to show here particularly simple and compatible with all the containers.
What you need
You really need just a few bundles:
Java Servlet API (2.4.0) [1]
OPS4J Pax Web – Service (0.5.1) [2]
OPS4J Pax Web Extender – Whiteboard (0.4.0) [3]
The Pax Web bundle [4] contains an embedded Jetty [6] servlet container, that is automatically started as soon as the bundle is deployed. The Pax Web Extender – Whiteboard bundle [5] provides a useful extension allowing developers to define new servlets on the fly.
How to develop an Hello Servlet
Well, nothing special, just an Hello Servlet!
public class HelloServlet extends HttpServlet
{
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.getWriter().write("Hello World");
}
}
OSGify your servlet
First of all, remember to add to your manifest the Import-Package statement:
Import-Package: javax.servlet,javax.servlet.http,org.osgi.framework;version="1.4"
Then, register a HttpServlet service in your activator:
public class Activator implements BundleActivator{
public void start(BundleContext context) throws Exception
{
Hashtable props = new Hashtable();
props.put("servlet-name", "Hello Servlet");
props.put("alias", "/hello");
context.registerService(HttpServlet.class.getName(), new HelloServlet(), props);
}
public void stop(BundleContext context) throws Exception {
}
}
Where the alias is the usual servlet-mapping.
Create your bundle and deploy it… then open your browser at http://localhost:8080/hello, and enjoy!
References
[1] Maven: javax.servlet, com.springsource.javax.servlet, 2.4.0
Repository:
id: com.springsource.repository.bundles.external
name: SpringSource Enterprise Bundle Repository – External Bundle Releases
url: http://repository.springsource.com/maven/bundles/external
[2] Maven: org.ops4j.pax.web, pax-web-service, 0.5.1
Repository:
id: OPS4J
name: OPS4J Repository
url: http://repository.ops4j.org/maven2
[3] Maven: org.ops4j.pax.web-extender, pax-web-ex-whiteboard, 0.4.0
Repository:
id: OPS4J
name: OPS4J Repository
url: http://repository.ops4j.org/maven2
[4] Pax web, http://wiki.ops4j.org/display/ops4j/Pax+Web
[5] Pax Web Extender Whiteboard, http://wiki.ops4j.org/display/ops4j/Pax+Web+Extender+-+Whiteboard
[6] Jetty, http://www.mortbay.org/jetty/
If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.
