Java Servlet池 [英] Java Servlet Pooling
问题描述
在Tomcat 6下的Servlets 101:
Servlets 101, under Tomcat 6:
有人可以指点我对例如最佳方式的一个很好的解释。在servlet启动时创建一个昂贵的Foo对象的集合,并将它们存放在我可以在处理每个请求时访问它们的地方?
Could someone kindly point me to a good explanation of the best way to eg. create a Collection of expensive Foo objects at servlet startup time and stash them somewhere where I can access them while processing each request?
我可以告诉至少有三个如何做到这一点,我在差异上有点模糊。我并不关心集群或算法来驱逐陈旧的条目或类似的东西,只是基础知识。
Near as I can tell there are at least three ways to do this and I am a bit fuzzy on the difference. I am not concerned with clustering or algorithms to evict stale entries or anything like that, just the basics.
干杯谢谢。
推荐答案
实现 ServletContextListener
,在 contextInitialized()
期间执行所需的加载任务,并将结果存储在应用范围由 ServletContext#setAttribute()
组成。它将在服务器启动期间调用,并且应用程序范围也可以在常规servlet中访问。
Implement a ServletContextListener
, do the desired loading task during contextInitialized()
and store the result in the application scope by ServletContext#setAttribute()
. It will be invoked during server's startup and the application scope is accessible inside regular servlets as well.
基本示例:
public class Config implements ServletContextListener {
public void contextInitialized(ServletContextEvent event) {
List<Foo> foos = fooDAO().list();
event.getServletContext().setAttribute("foos", foos);
}
}
将其映射到 web。 xml
通常的方式:
Map it in web.xml
the usual way:
<listener>
<listener-class>mypackage.Config</listener-class>
</listener>
以下是在常规servlet中访问它的方法:
Here's how to access it in regular servlets:
protected void doSomething(request, response) {
List<Foo> foos = (List<Foo>) getServletContext().getAttribute("foos");
}
以下是在JSP中访问它的方法:
And here's how you can access it in JSPs:
<c:forEach items="${foos}" var="foo">
${foo.someProperty}<br>
</c:forEach>
这就是说,我真的不知道这与servlet pool有什么关系。这个词毫无意义。
That said, I really don't see how that is related to "servlet pool". This term makes no sense.
希望这会有所帮助。
这篇关于Java Servlet池的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!