tags:

views:

43

answers:

1

I am now working on a web application project for the first time, the application includes registering and adding users to the database, now i wrote a java class called DatabaseManager that implements all database operations, and wrote the JSP page responsible for adding new users, if the registration is successful I need to add the user's details to the database, so I was wondering, do I need to create a instance of DatabaseManager and load the database driver and initialise the connection everytime a new user registers or is there a more efficient way to do it?

thanks

+2  A: 

Loading the database driver can be done just only once during webapp's startup. You can use a ServletContextListener for this. You could do the driver loading task in the constructor of the DatabaseManager class and instantiate it during contextInitialized() and store the instance in the application scope so that it is available to all servlets in the context (noted should be that JSP is in essence the wrong place for business logic).

Opening (and closing!) the Connection should really be done directly in the very same method block as you're executing the SQL query. It should certainly not be "cached" as a static/instance variable somewhere in your application logic. To improve connecting performance, the normal practice is to configure a connection pool to obtain the connections from. In every decent servletcontainer you can do this in flavor of a JNDI datasource.

Long story short, you can find a JSP/Servlet example utilizing the above techniques in this article which is by coincidence also using an use case of "register user".

BalusC
thanks BalusC, having followed your tutorial and your explanation here helped me connect all the stuff that I read about servlets.
Noona
You're welcome.
BalusC