Reputation: 184
I've been trying really hard to figure out how to bring in this database connection into my servlet, but failed, and hence this posting here.
Basically, I am using this code which I found my this site - one that is taught by BalusC.
public class Config implements ServletContextListener {
private static final String ATTRIBUTE_NAME = "config";
private DataSource dataSource;
@Override
public void contextInitialized(ServletContextEvent event) {
ServletContext servletContext = event.getServletContext();
String databaseName = servletContext.getInitParameter("pract1");
try {
dataSource = (DataSource) new InitialContext().lookup("java:/comp/env/jdbc/TestDB");
} catch (NamingException e) {
throw new RuntimeException("Config failed: datasource not found", e);
}
}
@Override
public void contextDestroyed(ServletContextEvent event) {
System.out.println("contextDestroyed....");
}
public DataSource getDataSource() {
return dataSource;
}
public static Config getInstance(ServletContext servletContext) {
return (Config) servletContext.getAttribute(ATTRIBUTE_NAME);
}
}
He explained that you have this class and the connection will start once for all the servlets, so I thought it's a good practice to do it.
Now, my problem is that I do not know how to bring the database connection which is set up in the Config, the context.xml file, etc. to work in the servlet.
Here's what I have attempted but it is not working out:
Connection con = null;
Config a = new Config();
con = (Connection) a.getDataSource();
DBConnect dbConnect = new DBConnect();
con = dbConnect.getConnection();
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT * FROM members");
I hope someone can tell me how to bring the connection into my doPost Servlet.
Upvotes: 0
Views: 136
Reputation: 11433
Use this:
Connection con = ((DataSource) a.getDataSource()).getConnection();
Instead of this:
Connection con = null;
con = (Connection) a.getDataSource();
DBConnect dbConnect = new DBConnect();
con = dbConnect.getConnection();
Assuming that you have set:
Config a = Config.getInstance(request.getServletContext());
Upvotes: 0
Reputation: 10497
Better way to use the connection created in ServletContextListner
is by setting it as a attribute in ServletContext like this :
event.getServletContext().setAttribute("connection_name", connection_object);
After this, you can use this connection_object
in any servlet like this :
connection_object = config.getServletContext().getAttribute("connection_name");
Upvotes: 1
Reputation: 26094
Your casting datasource to Connection
Connection con = null;
con = (Connection) a.getDataSource();
Please change to
DataSource dataSource= null;
dataSource = (DataSource) a.getDataSource(); // Your casting datasource to Connection
//get the connection from datasource
if (dataSource!= null) {
con = dataSource.getConnection();
}
if (con!= null) {
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT * FROM members");
}
Upvotes: 0