#Servlet #to #Database software communication: #Advance #Java #Servlet #Programming #Tutorial: To make servlet program gathering inputs from Database table and storing results in database table we need to see/observe servlet program interacting with database software. For this we need to JDBC code in Servlet program.
Three important operations of JDBC persistence logic are:
---------------------------------------------------------
1) Create JDBC connection object.
2) Use JDBC connection object to create other JDBC objects (like Statement, ResultSet objects ...) and to develop JDBC persistence logic.
3) Close JDBC connection object.
There are 3 approaches/Strategies to plan JDBC code in our servlet program.
-----------------------------------------------------------------------
1) Approach 1/Strategy 1:
-------------------------
Create JDBC connection object in the init()method.
Use this jdbc connection object in service(-,-) or doXxx(-,-) to create other jdbc objects and develop JDBC persistence logic.
Close the JDBC connection object.
Here (Approach 1) JDBC connection object must be taken as instance variable in our servlet program
Sample Code:
pulic calss TestSrv extends HttpServlet{
Connection con=null; //here assigning null is optional, because each global object is by default null holds.
public void init(){
--------// logic to create the JDBC connection object
--------
}
public void service(-,-)/doXxx(-,-) throws SE,IOE{
----//logic to use jdbc connection object and to develop
----// JDBC persistence logic
}
public void destroy(){
-----//logic to close JDBC connection object (i.e. con.close())
}
}
Adavantages of Approach 1:
All the request coming to servlet program from different browsers , will use one JDBC conncetion object, to interact with Database software. so the performance is good.
Disadavantages of Approach 1:
Here JDBC connection object is insance variable of servlet program, so its not threadsafe object by default, for this we need to work with SYNCHRONIZATION concept explicitly.