Skip to content

Undertow: Using existing Servlet instance

I am trying to replace in an existing application the embedded web server with Undertow as the old does not work correctly in some cases.

The embedded web server is used to server a few simple servlets. My main problem is that I can’t find a way to register an existing HttpServlet instance in Undertow.

All API methods I was able to find only accept an Class<? extends Servlet>. Also the servlet tutorials and others only use Class<? extends Servlet> for registering a servlet.

My Servlets however already exists and I need to use them directly as each servlet is already configured with certain parameters and thus can not be created by just providing a class name.

Is there any way to use an existing instance of a class that implements javax.servlet.Servlet directly in Undertow or is Undertow not usable for such a case?

Answer

It is possible to use an existing Servlet instance in Undertow by using the method Servlet.servlet(String, Class<? extends Servlet>, InstanceFactory<? extends Servlet> servlet):

Servlet myServletInstance = ...
Servlets.servlet("MessageServlet", MessageServlet.class, 
    new ImmediateInstanceFactory<Servlet>(myServletInstance))
            .addMapping("/*")

In this case the class parameter is ignored and instead of creating a new instance via constructor by Undertow internally, the provided servlet instance is used.