1

Im new in Java servlets, My question is: Can I use dataBaseHandler and conn variables as global variables in Servlet, and what negative consequences could be with this?

public class AddTrailerServlet extends HttpServlet {
    private Connection conn;
    private DataBaseHandler dataBaseHandler;

    doGet {
         dataBaseHandler = new DataBaseHandler();
    }
    doPost {
         dataBaseHandler = new DataBaseHandler();
    }
}
www.hybriscx.com
  • 1,129
  • 4
  • 22
Boris
  • 13
  • 5
  • There are multiple consequences but you can debug and manage that. also refer to this question - https://stackoverflow.com/q/55023282/8098322 – Onkar Musale Nov 13 '19 at 07:17
  • 2
    As you are new to Java servlets, I would strongly recommend to **NOT** use global variables in servlets at all, and definitely not for Connection etc. There is only **one instance** of the servlet in the container, so you will get in a lot of concurrency troubles in a real situation with parallel users. – Jozef Chocholacek Nov 13 '19 at 09:56

1 Answers1

1

You can create a util class which return database connection:

public class DataBaseHandler
{
   public static Connection getConnection()
   {
      try
      {
         Class.forName(driver);
         return DriverManager.getConnection(url + dbName, username, password);
      } catch (Exception e)
      {
         System.err.println(e);
         //Or your logic to handle exception
      }
   }
}

And your code goes like this:

public class AddTrailerServlet extends HttpServlet
{
   doGet()
   {
      try(Connection conn = DataBaseHandler.getConnection())
      {
         //Your custom code
      }
   }

   doPost()
   {
      try(Connection conn = DataBaseHandler.getConnection())
      {
         //Your custom code
      }
   }
}
ErShakirAnsari
  • 653
  • 7
  • 19