Search code examples
javatomcatservletshttpserver

ServletContextListener isn't invoked when using com.sun.net.httpserver.HttpServer


I use com.sun.net.httpserver.HttpServer in integration tests. It does its job but I've noticed that ServletContextListener's methods aren't invoked during tests. When I deploy the app to the real Tomcat server I can see its methods being called.

Below is the listener class:

package abc;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

@WebListener
public class StartupListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent event) {
        System.out.println("########################################");
    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {
        System.out.println("########################################");
    }
}

Here is how I start the HttpServer in the test:

@BeforeClass
public static void startServer() {
    URI uri = UriBuilder.fromUri("http://localhost/").port(8080).build();

    // Create an HTTP server listening at port 8080
    try {
        server = HttpServer.create(new InetSocketAddress(uri.getPort()), 0);
    } catch (IOException e) {
        e.printStackTrace();
        fail();
    }

    // Create a handler wrapping the JAX-RS application
    HttpHandler handler = RuntimeDelegate.getInstance().createEndpoint(new ApplicationConfig(), HttpHandler.class);
    // Map JAX-RS handler to the server root
    server.createContext(uri.getPath(), handler);
    // Start the server
    server.start();
}

Maven dependency:

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.0.1</version>
    <scope>provided</scope>
</dependency>

I removed @WebListener and inserted

metadata-complete="false"

and

<listener>
        <listener-class>abc.StartupListener</listener-class>
</listener>

in web.xml but it didn't help

What is the problem? Is there anything that needs to be setup?


Solution

  • What is the problem?

    HttpServer is not a servlet container and does not know about servlet api.

    Is there anything that needs to be setup?

    You need to setup a servlet container like jetty, which is frequently used for unit testing java based web applications.