views:

301

answers:

2

Is there a way for me to instantiate the Spring MVC DispatcherServlet in code rather put it in the web.xml and have it be instantiated by the web server?

The reason for this is that I want to check a memCache to see if I have already recently rendered the page that is being requested and if so just return from the memCache, rather than going through Spring MVC and the controllers.

The ~2 second instantiation of the DispatcherServlet is significant because I am using Google App Engine and that might end up being an additional 2 seconds the user has to wait for their page.

I have tried

dispatcherServlet = new DispatcherServlet();
dispatcherServlet.init();
dispatcherServlet.service(request, response);

but I get this exception on the init call:

[java] java.lang.NullPointerException
[java]         at org.springframework.web.servlet.HttpServletBean$ServletConfigPropertyValues.<init>(HttpServletBean.java:196)
[java]         at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:114)

Basically, what I'm looking for is a way to instantiate a servlet in code without having to specify it in web.xml and not have to call

getServletConfig().getServletContext().getServlet("dispatcherServlet");
A: 

Unless Google App Engine does something really weird, the DispatcherServlet is only instantiated once, on application startup.

If you want to cache page response as you mention, I would suggest implementing this as a HandlerInterceptor (which you can apply to any URL pattern you like), which gives you hooks to plug in logic in either pre- or post-invocation of your controller.

matt b
With the google app engine, it starts and stops JVM instances a lot. If your application is idle for a couple minutes, it will stop the JVM and there will be a whole new application startup with the next request, including DispatcherServlet instantiation
Kyle
That sounds like applications which have considerable startup logic/activity would be a bad choice for GAE
matt b
+1  A: 

DispatcherServlet is a servlet, so you should call init(ServletConfig) instead of init() to initialize it.

axtavt
Well, that worked perfectly thanks! BTW its init(ServletConfig). And the servlet config is easily gotten with a call to getServletConfig().
Kyle