Reputation: 15792
I have my servlets configuration in class I
that extends ServletContainerInitializer
. I register servlets and define mappings there. I don't want to do same work in my integration tests. Is there are common way to reuse I
config in my jetty tests?
So I have 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("/*");
}
}
And tests like
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();
How I can do it without duplication?
Upvotes: 0
Views: 524
Reputation: 3622
you need to add a listener to jetty's life cycle
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();
tested on jetty-8.1.5.v20120716
Upvotes: 1