简体   繁体   English

使用com.sun.net.httpserver.HttpServer时不调用ServletContextListener

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

I use com.sun.net.httpserver.HttpServer in integration tests. 我在集成测试中使用com.sun.net.httpserver.HttpServer It does its job but I've noticed that ServletContextListener's methods aren't invoked during tests. 它完成了它的工作,但我注意到在测试期间未调用ServletContextListener's方法。 When I deploy the app to the real Tomcat server I can see its methods being called. 当我将应用程序部署到真正的Tomcat服务器时,可以看到其方法被调用。

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: 这是我在测试中启动HttpServer的方法:

@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: Maven的依赖:

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

I removed @WebListener and inserted 我删除了@WebListener并插入

metadata-complete="false"

and

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

in web.xml but it didn't help web.xml但没有帮助

What is the problem? 问题是什么? Is there anything that needs to be setup? 有什么需要设置的吗?

What is the problem? 问题是什么?

HttpServer is not a servlet container and does not know about servlet api. HttpServer不是servlet容器,也不知道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. 您需要设置一个像jetty这样的servlet容器 ,该容器经常用于基于Java的Web应用程序的单元测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM