0

when developing web application using JSP and servlet this is the biggest question in my mind that where to put the CODING OF DATABASE CONNECTION...

In servlet, if we put the connection code inside the service() (or doXXX ()) method then for every request a connection is established between the application and the database; and this leads to consumption of time and resources so this is not a good option...

And if we put the connection code inside the init() method (by initializing the instanse variable) then only one connection is made and all the user's requests can use that same connection for communication with the database in service() (or doXXX ()) method; and when we think about simultanious requests, this may lead to synchronization problem because all the requests are using the same connection...

So what is the elegant solution of this problem ?

Divyesh
  • 11
  • 4
  • You can have your server maintain the pool and then obtain a connection using JNDI. For Tomcat for example: https://tomcat.apache.org/tomcat-7.0-doc/jndi-resources-howto.html#JDBC_Data_Sources. Otherwise you could init the database pool in the ServletContext using a http://docs.oracle.com/javaee/6/api/javax/servlet/ServletContextListener.html and obtain connections in your Servlet via the ServletCOntext – Alan Hay Aug 09 '16 at 12:27
  • JDBC is fairly resilient to multiple requests... – OneCricketeer Aug 09 '16 at 12:28
  • JDBC is not multithreaded. Be careful. – duffymo Aug 09 '16 at 12:31

1 Answers1

1

You have a fundamental misunderstanding of what JSP is.

Java Server Pages, especially when you use JSTL, are compiled into servlets that run on the server. They are HTML factories that create markup and stream it to the browser.

With that said, JSPs are not the place to put database access or logic of any kind. They should be for rendering markup - that's all.

Database connections should be pooled by your Java EE container. They should be managed by a service layer that knows about units of work and transactional behavior. The service layer should get a connection, give it to repository classes that interact with the database, and close the connection before giving it back to the pool.

If it's a choice between JSP and servlet, I've vote for neither. Create interface based POJOs for services and repositories that can be tested independently without a Java EE container. Give servlets references to the services to fulfill requests from the client.

JSPs are an old J2EE 1998 vintage technology. The world has gone in the direction of HTML5, CSS3, JavaScript, and jQuery for web user interfaces and REST services for the back end. You should consider it, too.

duffymo
  • 305,152
  • 44
  • 369
  • 561