在Jetty测试中重用ServletContainerInitializer

时间:2013-03-15 11:50:59

标签: java testing jetty servlet-3.0

我在课程I中有我的servlet配置,扩展了ServletContainerInitializer。我注册servlet并在那里定义映射。我不想在集成测试中做同样的工作。是否有在我的码头测试中重用I配置的常用方法?

所以我有I

public class I implements ServletContainerInitializer {
    public void onStartup(Set<Class<?>> c, ServletContext ctx) throws ServletException   {
        Servlet servlet = new MyServlet();
        ctx.addServlet("foo", servlet).addMapping("/*");
   }
}

等测试一样
    Server server = new Server(0);
    Context servletContext = new Context(server, "/", Context.SESSIONS);


    Servlet servlet = new MyServlet();                           //Duplicated
    servletContext.addServlet(new ServletHolder(servlet), "/*"); //Duplicated

    server.start();

如何在不重复的情况下完成这项工作?

1 个答案:

答案 0 :(得分:1)

你需要为jetty的生命周期添加一个监听器

public class JettyStartingListener extends AbstractLifeCycleListener {

    private final ServletContext sc;

    public JettyStartingListener(ServletContext sc){
        this.sc = sc;
    }

    @Override
    public void lifeCycleStarting(LifeCycle event) {
        try {
            new I().onStartup(new HashSet<Class<?>>(), sc);
        } catch (ServletException e) {
            throw new RuntimeException(e);
        }
    }

}

Server server = new Server(8080);
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
server.setHandler(context);
context.addLifeCycleListener(new JettyStartingListener(context.getServletContext()));
server.start();
server.join();

在jetty-8.1.5.v20120716上测试