I currently learn the JSP & Servlet in java web with tomcat 9.0,
I saw some websites say that a servlet will be initialized only once, and the
destroy()
method will be called when the server want to terminate the life of that servlet,and a servlet will be used for multiple same type requests, http request for example,
and database connection resources are important.
So, I think, I should make the Connection object
as a member of my Servlet so that I won't need to establish a new connection every time when there is a new http request, and close the connection when the servlet is destroyed.
like this:
public class LoginServlet extends HttpServlet {
private Connection conn;
// init, get mysql Connection
public TeamBlueServlet() {
initiate();
}
private void initiate() {
// do something and get connection...
this.conn = controller.getConnection();
}
// close connection in this method
@Override
public void destroy() {
// try, catch
this.conn.close();
}
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
// do some query
try {
ResultSet resultSet = ...;
PreparedStatement statement = ...;
} catch (SQLException e) {
...
} finally {
close(statement, resultSet);
}
}
private void close(PreparedStatement sta, ResultSet rs) {
try {
if(sta !=null) sta.close();
} catch (SQLException e) {
logger.error(e.getMessage());
}
try {
if(rs !=null) rs.close();
} catch (SQLException e) {
logger.error(e.getMessage());
}
}
}
But I also saw some say that we should, open connections as late as possible & close connections as soon as possible.
Therefore I get confused, I want to know if I need to make the connection and close it with each query or should I keep the connection open? I know there is something called connection pool probably can solve this problem, but I want to know in this case, which would be better.
Any help would appreciate, thanks.