[Logo]
Forums Register Login
Connection to DB using JNDI in Servlets Init Method Issue
Dear Team,

In my application, From my JSP Iam calling servlets on POST request. In my servlets using JNDI Datasource to create a database connection (SQL) to execute INSERT query. Inside init method, I have created this connection. Problem now is that for every refresh of jsp page, init method is not executing. I knew it will be called only once. How to handle it ?



servlets-sourcecode.JPG
Servlets Sourcecode
[Thumbnail for servlets-sourcecode.JPG]
JSP-sourcecode.JPG
JSP sourcecode
[Thumbnail for JSP-sourcecode.JPG]
Please do not post screenshots of your code. You can copy paste your code (please do UseCodeTags)
I hope your con object is a static one for connection. So, you should be good to use it in doPost method to execute the statements.

Why do you want to create a new connection on each request? If you want to do that, then you can put that logic in your doPost() method but I don't see any use of doing it for each and every request.
 

Vaibhav G Garg wrote:I hope your con object is a static one for connection. So, you should be good to use it in doPost method to execute the statements.

Why do you want to create a new connection on each request? If you want to do that, then you can put that logic in your doPost() method but I don't see any use of doing it for each and every request.



Actually you should not have a static connection object.
Also, don't put any instance variables in servlets (unless they are stateless proxies).

When using connections in a container, get the connection from a datasource obtained using JNDI lookup, use the connection and close it immediately after. Every interaction with the database must do that and never try to reuse a connection used by a previous task. The reasons are
1.) It's not wasteful of resources as you might think because the pooling is provided by the container so when you close a connection it's actually just returned to the pool.
2.) Leaving connections open for reuse by next tasks results in some connections never being closed because the next tasks are not always guaranteed to run.
3.) Most databases have timeouts on connections so if you keep a connection open for too long it will timeout and the next task will just fail anyway because it has a 'stale' connection.


This thread has been viewed 601 times.

All times above are in ranch (not your local) time.
The current ranch time is
Sep 24, 2018 10:20:22.