Witam!
Mam kolejne pytanie, przy pisaniu servletu łącze się z bazą danych przez takie coś:
public final class YourClass extends HttpServlet {
Connection con = null;
public void init() throws ServletException {
String url = getServletContext().getInitParameter("url");
String uid = getServletContext().getInitParameter("uid");
String pwd = getServletContext().getInitParameter("pwd");
try {
//Register the JDBC driver
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch( Exception e ) {
e.printStackTrace();
}//end catch
//Get a connection to the database
try {
con = DriverManager.getConnection(url, uid, pwd);
} catch( Exception e ) {
e.printStackTrace();
}//end catch
}//end init()
public void destroy() {
try {
//Close the connection to the database
con.close();
} catch( Exception e ) {
e.printStackTrace();
}
}
public void doGet(HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException{
try {
[...]
Statement st = con.createStatement();
[ more JDBC code ]
}
catch (SQLException e) {
[ ... ]
}
}
Pytanie czy to jest dobre rozwiązanie? Bo kod w każdym servlecie trzeba powtarzać nie można w jakiś sposób zaimplementować połączenie bez powtarzania kodu?? Może jest jakiś schemat postępowania?
Dzięki z góry za pomoc!