I am refactoring others code. The one thing I notice is that of the manner on how the system is getting a connection from the connection pool.
Sample is like this. On every call of the service method, the system is making a context lookup on the JNDI for the datasource.
public class CheckinServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
//Obtain Connection
InitialContext initialContext = new InitialContext();
javax.sql.DataSource ds = (javax.sql.DataSource) initialContext
.lookup("jdbc/mysqldb");
java.sql.Connection conn = ds.getConnection();
//business logic
//redirect
} finally {
conn.close();
}
}
}
I do think that there is a performance hit on doing this every time. I am thinking of another way around these on how to retrieve a connection from a connection pool.
I am thinking about using the servlet’s init() method but I think that is not optimal.
Do it once in a
ServletContextListenerinstead of everytime ininit()of many servlets. ThecontextInitialized()method is executed only once during webapp’s startup.Configure it as follows in
web.xml:You can obtain it in your servlet as follows (
init()ordoXXX()method, you choose):I’d however refactor it a step further, JDBC code should preferably be placed in its own classes, not in servlets. Lookup the DAO pattern.