Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I call the Config.java in my servlet?
    text
    copied!<p>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.</p> <p>Basically, I am using this code which I found my this site - one that is taught by BalusC.</p> <pre><code>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); } } </code></pre> <p>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.</p> <p>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.</p> <p>Here's what I have attempted but it is not working out:</p> <pre><code>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"); </code></pre> <p>I hope someone can tell me how to bring the connection into my doPost Servlet.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload