0

I我在扩展类中有我的 servlets 配置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();

我怎样才能做到不重复?

4

1 回答 1

1

您需要在码头的生命周期中添加一个侦听器

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 上测试

于 2013-07-26T14:45:00.587 回答