Is there a way for me to instantiate the Spring MVC DispatcherServlet in code rather put it i开发者_开发问答n 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");
DispatcherServlet
is a servlet, so you should call init(ServletConfig)
instead of init()
to initialize it.
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.
精彩评论