Java servlets and database connection pooling

僤鯓⒐⒋嵵緔 提交于 2019-12-04 09:51:29

1) I'd say that standard practice is to set up a connection pool as a JNDI resource in the context descriptor, which would not be a per-servlet thing to do.

2) You'll want to implement and declare a ServletContextListener.

To be honest, I don't really know what you are talking about. Maybe you could provide the samples you looked at.

To me, a "real" connection pool should be totally Servlet agnostic and using a connection pool on a per Servlet basis is a more a usage detail (and a bad one IMO). Just look at DBCP or c3p0 for good examples of connection pools that you may use in an "out-of-container" context.

Also note that most (if not all) containers actually provide their own connection pool implementations (sometime based on the previous mentioned examples) and I don't see any good reason to not use them. The standard way to use them is to get a DataSource registered with a JDNI naming service. Today, the DataSouce is most of time injected through IoC. In old days, the Service Locator pattern was often used.

In the case of Jetty, have a look at DataSource Examples in the documentation.

My question is, why is that preferable to something like a global pool of db connections?

It is not! All servlets should share connections in a pool!

Also, since I'm thinking about implementing such a pool.

There are already ways (Spring IoC) to inject pooled connections which are container managed.

. Is there a way to have a class initialized before the servlets(I'm using jetty btw)?

The IoC container can bootstrap every resource and servlet!

You can spring-wire servlets by registering a Spring dispatcherServlet and a xml containing the mappings and servlets as bean definitions!

Use the following definitions if you only want to inject the connection and leave the rest of the servlet as it is:

<bean name="simpleServletHandlerAdapter"
class="org.springframework.web.servlet.handler.SimpleServletHandlerAdapter" />


<bean name="simpleServletPostProcessor"
class="org.springframework.web.servlet.handler.SimpleServletPostProcessor" />

It is very frequent for web containers to provide a ConnectionFactory (or similar) using JNDI which uses a pool of connections, but the way to configure it is not standardized.

Please see http://docs.codehaus.org/display/JETTY/DataSource+Examples for how it is done with Jetty.

One advantage of having a connection pool per servlet is that if one of the servlets misbehaves and uses all its available connections, then other servlets will still have connections available in their seperate pools. This increases stability of your application.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!