Question

The problem is simple, but I'm struggling a bit already.

Server server = new Server(8080);  
Context context = new Context(server, "/", Context.NO_SESSIONS);
context.addServlet(MainPageView.class, "/");
context.addServlet(UserView.class, "/signup");
server.start();

That's a pretty standard piece of code that you can find anywhere in Jetty world. I have an application that embeds Jetty as a servlet engine and has some servlets.

Instantiation of some of these servlets requires heavy work on startup. Say – reading additional config files, connecting to the database, etc. How can I make the servlet engine instantiate all servlets eagerly, so that I can do all the hard work upfront and not on the first user request?

Was it helpful?

Solution

I'm not sure why using Guice make's Justin's option not work for you. What exactly is getting injected in? I'm not sure if this would help you at all because it is very similar to what Justin wrote above but if you do it this way, Jetty will do the actually instantiating.

Context context = new Context(server, "/", Context.NO_SESSIONS);
ServletHolder mainPageViewHolder = new ServletHolder(MainPageView.class);
// Do this to force Jetty to instantiate the servlet
mainPageViewHolder.getServlet();  
context.addServlet(mainPageViewHolder, "/");

OTHER TIPS

Use the Context.addServlet overload that takes a ServletHolder. ServletHolder is a class that accepts either a Class or a Servlet instance.

Servlet myServlet = new MyServlet();
ServletHolder holder = new ServletHolder(myServlet);
context.addServlet(holder, "/");

This assumes Jetty 6. I think it will work for Jetty 7 as well.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top