I open my servlet database (JDBC-ODBC) connection in the init() method. I close it in the destroy() method. My database is configured to close the connection automatically after 10 minutes of idle time. This creates problems since the servlet does not call the destroy() method and the init() method remains in the memory. within that time and after 10 minutes if a user requests that servlet it throws an exception saying : not logged on. why is this happening and if you can provide a solution to this problem by giving a sample code?

Jorge Jordão

The problem seems to be the server takes longer than 10 minutes to release a servlet instance.

This can probably be configured, but what you should do instead is open the connection, execute the statements and close the connection all in the service (doGet or doPost) method, instead of keeping it opened. You can still load the driver class in init, since that needs to be done only once.

Example: (notice I'm using String constants for DB access for simplicity, I should be reading that information from an outside source):
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;

public class DBServlet extends HttpServlet {

    private static final String DB_DRIVER = "sun.jdbc.odbc.JdbcOdbcDriver";
    private static final String DB_URL = "jdbc:odbc:Northwind";
    private static final String DB_USER = "";
    private static final String DB_PASSWORD = "";    

    public void init(ServletConfig config) throws ServletException {
        try {	    
        } catch (ClassNotFoundException ex) {
            throw new UnavailableException("JDBC Driver " + DB_DRIVER + " not found.");
    public void doPost(HttpServletRequest request, HttpServletResponse response) 
        throws IOException, ServletException {
        try {
            Connection conn = DriverManager.getConnection(DB_URL,DB_USER,DB_PASSWORD);
            // execute statements (and process results)
        } catch (SQLException ex) {
            // handle exception


If you find this approach too slow, consider using a connection pool.

Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



About | Sitemap | Contact