This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Servlets and the fly likes Database connection in servlet Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Servlets
Bookmark "Database connection in servlet" Watch "Database connection in servlet" New topic
Author

Database connection in servlet

Michael Keisu
Ranch Hand

Joined: Oct 08, 2009
Posts: 30
Hi, I'm just starting out with Servlets & JSP(the book I'm reading is Head First Servlets and JSP).

What I'm wondering about something is something I read in the book, it says the following:
If you have initialization code (like getting a database connection or registering yourself with other objects), then you’ll override the init() method in your servlet class.


Regarding databases, isn't it a bad thing to keep database connection open for long(which might happen with many GET or POST requests running in separate threads)? Also, what happens when the multiple threads try to access it?

I don't have much experience in either databases or servlets.
Shailesh Narkhede
Ranch Hand

Joined: Jul 10, 2008
Posts: 368
This is just an example, when you want to anything that you need to use in DoGet() or DoPost() method( service() ) that initialization of that resources needs to be happen in init() method. and all destruction of resources can be done in destroy() method.

Yes, keeping database connection open for long time is not good, In real time system generally using connection pool to maintain connections.

And class level variable in servlets are not thread safe. variable that going to be part of Service() method is thread safe.


Thanks,
Shailesh
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 60738
    
  65

Yes, it's just a beginner's example and nothing you would do in real code.

In fact, dealing with the databases at all in the controller layer is a bad idea. DB access should be firmly ensconced in the model/data layer.


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
Michael Keisu
Ranch Hand

Joined: Oct 08, 2009
Posts: 30
Ah. Thanks for the replies. It makes me a little uneasy about the book, I don't want to learn bad habits. Perhaps it'll discuss the better ways of doing things later, though.
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 60738
    
  65

As an author I know that sometimes it's hard to come up with basic examples that demonstrate a principle, while still sticking to best practices whose understanding requires more advanced concepts that have yet to be introduced. But, yeah, I would have tried to come up with a better example of what init() can be used for.

Say.... reading init-variables into read-only class variables for later use, or initializing a cache for memoizing values that are compute-intensive.
Graeme Byers
Ranch Hand

Joined: Apr 16, 2004
Posts: 127
The recommended way is to implement the Data Access Object (DAO) pattern (Alur "Core J2EE Patterns").
This author's complete example is spot on : http://balusc.blogspot.com/2008/07/dao-tutorial-data-layer.html.
To understand it , begin with his batch driver DAOTest.

However he fails to implement correctly the far more important Model-View-Controller (MVC) pattern.
Notice how the business logic methods in his mymodel.UserForm class have an HttpServletRequest parameter.

You will need some knowledge of servlets and JSP but don't get too involved - the skills in demand are Spring and Hibernate.
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 60738
    
  65

Graeme Byers wrote:You will need some knowledge of servlets and JSP but don't get too involved - the skills in demand are Spring and Hibernate.

I do not think that this is particularly good advice. Firstly, Hibernate and JSP/Servlets have no intersection. The fact that Hibernate skills are in demand has nothing at all to do with JSP and Servlets. Secondly, by "Spring" I assume what was meant was the SpringMVC web application framework. A sound knowledge of JSP and Servlets is necessary for using SpringMVC (and indeed, any other web application framework) to its best advantage.

So my advice would be to continue to learn JSP and Servlets quite well. This knowledge will serve you well no matter what other frameworks you may decide to use at some point in the future.
Mariya Antony christopher
Ranch Hand

Joined: Jan 24, 2012
Posts: 49

hi just try the following code for database connectivity for beginners
class.forName("sun.jdbc.odbc.JbdcOdbcDriver');
Connection ch=DriverManager.getConnection("Jdbc:Odbc:dsnname");
PreparedStatement ps=ch.prepareStatement("insert into tablename values(?,?)");
ps.setString(1,value);
ps.setString(2,value);
ps.executeUpdate();

then try JPA it will ore flexible for CRUD operation
Have anice day
Michael Keisu
Ranch Hand

Joined: Oct 08, 2009
Posts: 30
Bear Bibeault wrote:
Graeme Byers wrote:You will need some knowledge of servlets and JSP but don't get too involved - the skills in demand are Spring and Hibernate.

I do not think that this is particularly good advice. Firstly, Hibernate and JSP/Servlets have no intersection. The fact that Hibernate skills are in demand has nothing at all to do with JSP and Servlets. Secondly, by "Spring" I assume what was meant was the SpringMVC web application framework. A sound knowledge of JSP and Servlets is necessary for using SpringMVC (and indeed, any other web application framework) to its best advantage.

So my advice would be to continue to learn JSP and Servlets quite well. This knowledge will serve you well no matter what other frameworks you may decide to use at some point in the future.


Yes, I did get the impression Servlets and JSP was a prerequisite for some web application frameworks. Anyway, my class has yet to start with Servlets,JSP and web applicaiton frameworks, I'm studying it at home since my education is a pretty short one (only 2 years), and I yet question if they can teach me everything I need to know(though JSP & Servlets, SpringMVC and/or Struts is planned), especially since Java Basics and OOP was crammed into it for the first few months. Almost everyone gets work after finishing it, so they must be doing something right but it never hurts to study more in depth..

Anyway, I'll be attending a developer conference JFokus(Primarily Java), one of the talks will be comparison of web frameworks, I hope to learn more there.
Daniel Val
Ranch Hand

Joined: Jan 09, 2012
Posts: 44
Michael Keisu wrote:Hi, I'm just starting out with Servlets & JSP(the book I'm reading is Head First Servlets and JSP).

What I'm wondering about something is something I read in the book, it says the following:
If you have initialization code (like getting a database connection or registering yourself with other objects), then you’ll override the init() method in your servlet class.


Regarding databases, isn't it a bad thing to keep database connection open for long(which might happen with many GET or POST requests running in separate threads)? Also, what happens when the multiple threads try to access it?

I don't have much experience in either databases or servlets.



The other people already told you to put the stuff in the doGet etc - or more generally in service();

However, from experience, even more than that: try not to put anything in the init method. If it crashes, your app will not deploy properly.

Try to initialize all the resources on demand. You need to cache them? Use some singleton like construct. You don't? Then get them when you enter in the service method and release them before you go out. Preferrably in some finally construct of a try / catch / finally so that you know for sure that they were released no matter what.

Example: database connection: usuall you take it from a connection pool accessible via JNDI / DataSource. The pool has a limited number of connections. You get the connection, you use it within your servlet call then you close it (remember the finally stuff mentioned above) and it will be released to the pool. You don't do that, it is called connection leak and your connection pool will go down RAPIDLY.



- close is a method you define / implement in the servlet that will check first whether the connection is not null and then will close it, everything between a try / catch that will ensure this stuff will never crash
- if you put conn.close() there, it will work, but if conn is null (that means the mere process of obtaining the connection crashed) that will throw an error and because you are out of the try stuff - it will be propagated to the container who will show some garbled stuff on the screen.
- getConnection() is a method that you implement that will retrieve the connection from whatever pool you have configured in your app server
- another thing - don't throw exception to the container. Instead prepare a nice error message that you show on the page. If you throw the error to the container - will look awful.
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 60738
    
  65

Daniel Val wrote:The other people already told you to put the stuff in the doGet etc - or more generally in service();

It is generally considered a poor practice to override service().

However, from experience, even more than that: try not to put anything in the init method. If it crashes, your app will not deploy properly.

If it "crashes", the app should fail deployment. It means something is seriously wrong. Avoiding using init() for initialization for such a reason is nonsense.

another thing - don't throw exception to the container. Instead prepare a nice error message that you show on the page. If you throw the error to the container - will look awful.

Yes, throw the exception to the container. But, define error handlers to display the errors in a user-friendly manner. Hard-coding error handling in each controller or page is a recipe for disaster.

And, as already mentioned, database connections should be managed in the data/model layer, not in the controllers.
Daniel Val
Ranch Hand

Joined: Jan 09, 2012
Posts: 44
Bear Bibeault wrote:
Daniel Val wrote:The other people already told you to put the stuff in the doGet etc - or more generally in service();

It is generally considered a poor practice to override service().


I agree;

Bear Bibeault wrote:
However, from experience, even more than that: try not to put anything in the init method. If it crashes, your app will not deploy properly.

If it "crashes", the app should fail deployment. It means something is seriously wrong. Avoiding using init() for initialization for such a reason is nonsense.


No, there are solutions. It depends, but personally for a number of years I moved everything out of init, actually I no longer override init in servlets. No more state stored in the servlets, thus no need for init.

The reasons:

Let's say you are in the middle of a five hours deployment window. Your servlet init loads / caches something from an LDAP server. If the LDAP server is down (it is in maintenance together with your app and with other 50 apps), your app will not deploy because init will fail. You figure out what happens and try again to deploy when the LDAP is up, then it will work but this is a hassle.

A better approach: move the data caching in a singleton like construct, access that singleton from your servlet, have no code in the init or no init at all.

- The app will deploy no matter what
- When all the resources are available the application will work fine, but nevertheless regardless of the state of the external dependencies, the app will deploy ok from the first attempt.
- Till the dependencies are not available, the singletons will not instantiate


Bear Bibeault wrote:
another thing - don't throw exception to the container. Instead prepare a nice error message that you show on the page. If you throw the error to the container - will look awful.

Yes, throw the exception to the container. But, define error handlers to display the errors in a user-friendly manner. Hard-coding error handling in each controller or page is a recipe for disaster.


Was working like that and actually the handler would forward to one error page, but then realized it was not satisfactory. There are two types of errors, business and system. Business exception: they are business as usual, you need to set some error messages and maybe to change some css to highlight some edit fields and then return to the page. Same page, with the same previous state (so that you can take it from there and correct the errors). Sending this to the container and processing it with the error handling would be a hassle.

So it really make sense to send only the system errors to the container, but even there we spotted issues: normally the only system errors we got were the app inability to secure some database connection from the pool. In this case, we would send the error to the container as you mentioned, there was some error handler that would wipe out the session and forward to the error page.

But then we started working otherwise:
- process the error in the controller (one method call and the method was defined in some base class)
- set general error message
- return to the page with page state intact.

Guess why we did that: because if you try again it would usually work without issues.

So that's why I am not so keen to use container error handlers anymore with some exceptions.

Bear Bibeault wrote:
And, as already mentioned, database connections should be managed in the data/model layer, not in the controllers.


This I agree, however the gentleman was trying to get something working, did not want to get in detail about MVC stuff here.

D.

Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 60738
    
  65

Daniel Val wrote:No more state stored in the servlets, thus no need for init.

There are other things than storing state that might be done in initialization. And sometimes state is needed -- though I will store state in contexts rather than the servlet itself.

If you have structured your apps such that no initialization is needed, that's fine -- but to say that initialization should not be performed in init() is just flat-out wrong and counter to the intentions of the Servlet Specification.

There are two types of errors, business and system. Business exception: ...

"business errors" are generally not handled with exceptions.

Daniel Val
Ranch Hand

Joined: Jan 09, 2012
Posts: 44
Bear Bibeault wrote:
Daniel Val wrote:No more state stored in the servlets, thus no need for init.

There are other things than storing state that might be done in initialization. And sometimes state is needed -- though I will store state in contexts rather than the servlet itself.

If you have structured your apps such that no initialization is needed, that's fine -- but to say that initialization should not be performed in init() is just flat-out wrong and counter to the intentions of the Servlet Specification.


Till now I really did not see situations in which I cannot move any servlet initialization in some singleton based construct, linked to the servlet context or not...

Bear Bibeault wrote:
There are two types of errors, business and system. Business exception: ...

"business errors" are generally not handled with exceptions.



Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 60738
    
  65

Singletons are generally considered a poor pattern. I'm rather agnostic on it myself.

My main issue is that you seem to be saying "Don't do initialization in init(), do it in service()" and I disagree with that. The lifecycle methods are there for a reason and they should be used appropriately. If you're doing something that doesn't require initialization, then obviously there's no need to override init().
Daniel Val
Ranch Hand

Joined: Jan 09, 2012
Posts: 44
Bear Bibeault wrote:Singletons are generally considered a poor pattern. I'm rather agnostic on it myself.

My main issue is that you seem to be saying "Don't do initialization in init(), do it in service()" and I disagree with that. The lifecycle methods are there for a reason and they should be used appropriately. If you're doing something that doesn't require initialization, then obviously there's no need to override init().



No, from service() I call the singleton(s) which would be initialized on demand (first time they are accessed). It is not quite in service.

In terms of singletons, indeed there are issues and some controversy, but for me they were solution saviours for simple caching etc more than one time, so what can I do...

D
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 60738
    
  65

If the initialization is application wide, a context listener is a better place to put one-time initialization. And it doesn't need to be a singleton. Creating a single instance of a class and placing it in app context once serves the same purpose without the downsides associated with true singletons.

Sure, this isn't "just in time" initialization, but JIT isn't really needed when a single instance is being created. JIT is most useful for large numbers of operations that would hinder performance if performed all at once.
 
 
subject: Database connection in servlet
 
Similar Threads
Reconnecting to the Database
Initialising Database connections with JSP
jsp and servlets with jdbc
Max number of threads in a JVM
servlet-applet