简体   繁体   English

Spring MVC DispatcherServlet的延迟实例化?

[英]Lazy Instantiation of the Spring MVC DispatcherServlet?

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? 我有没有办法在代码中实例化Spring MVC DispatcherServlet而不是将其放入web.xml并由Web服务器实例化?

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. 这样做的原因是,我想检查一个memCache来查看我是否最近已经渲染了所请求的页面,如果是,则仅从memCache返回,而不是通过Spring MVC和控制器。

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. DispatcherServlet的〜2秒实例化非常重要,因为我使用的是Google App Engine,最终可能需要用户再等待2秒钟才能等待其页面。

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 基本上,我要寻找的是一种在代码中实例化servlet的方法,而不必在web.xml中指定它并且不必调用

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

DispatcherServlet是一个Servlet,因此您应该调用init(ServletConfig)而不是init()进行初始化。

Unless Google App Engine does something really weird, the DispatcherServlet is only instantiated once, on application startup. 除非Google App Engine做的事情确实很奇怪,否则DispatcherServlet在应用程序启动时只会实例化一次。

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. 如果您要缓存所提到的页面响应,我建议将其实现为HandlerInterceptor (可以将其应用于您喜欢的任何URL模式),这使您可以在调用之前或之后插入逻辑控制器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM