0

I am a new java programmer and having issues with Servlets without use of JSP. I made a simple java application with a SingletonDBConnect class that makes a connection to Access.mdb or MAMP db without any issues and will return a connection object to run any type of statements I like.

The problem is that I created a dynamic web project and made a simple servlet, I brought all the other classes that run my DB code but When I try to call my singleton class that establishes and returns a connection from inside the servlet it doesnt make the connection. I tried this several ways, everything works fine if I dont use the servlet but trying to call the singleton class to simply get a conn object back, it doesn't work. I dont want to write all my connection code inside my servlet in any way or any statement code, I would simply like to call different java classes I made and get the conn, stmt etc back and use it in the servlet. Can someone tell me how or if its even possible. Below is my code that returns NULL connection but w/o servlet use it works wonders....

@WebServlet("/DBServlet")
public class DBServlet extends HttpServlet {

    private static Connection conn=null;
    public void init(){
        SingletonDBConnect.getInstance().setDBType(DBTypeEnum.Access);
        conn= SingletonDBConnect.getInstance().getConnection();
        SingletonDBConnect.getInstance().close();
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        PrintWriter pen= resp.getWriter();
      if(conn==null){

            pen.write("Not connected");
      }else
          pen.write("Its working");     
    }
}
Luke Woodward
  • 56,377
  • 16
  • 76
  • 100
HKM
  • 1
  • 3
  • 1
    You really should **not** use a singleton connection for something that can be used concurrently, it can lead to race conditions and other hard to diagnose problems. Also what exactly does `SingletonDBConnect.getInstance().close();` do? I'd guess this will close the connection you just created. – Mark Rotteveel Mar 30 '18 at 13:39
  • Yes. that's just to close the connection. So I tried making a connection without using any other class and instead doing it all inside the servlet with exact same info and it still doessn't connect. When I run the project as a java application it runs fine and connects to the DB but when I run on server it says "No suitable driver found"... yet same project run as an application connects just fine. – HKM Mar 30 '18 at 18:45
  • See: https://stackoverflow.com/questions/1911253/the-infamous-java-sql-sqlexception-no-suitable-driver-found – Mark Rotteveel Mar 31 '18 at 06:37

0 Answers0