Ash
Ash

Reputation: 128

Connect to Datasource without resource-ref in web.xml

I have a web application running on tomcat7. The tomcat7 and a global datasource configuration component are part of a jetty portal. Now, I can setup global datasources on the portal which get added to the context.xml (of my application on tomcat) as a ResourceLink. I want to know if there is a way to connect to these datasources through my application jdbc code without putting in a resource-ref in my web.xml.

(This will help me connect to new datasource name without redeploying my WAR file just to add new resource-ref tags)

Upvotes: 0

Views: 4379

Answers (2)

Paul Vargas
Paul Vargas

Reputation: 42030

If you are using Apache Tomcat 7, you can use @Resource in a servlet for inject the datasource.

Add the file context.xml in the META-INF directory, local to the project:

<?xml version="1.0" encoding="UTF-8"?>
<Context antiJARLocking="true" path="/TestResource">
  <Resource name="jdbc/test" 
            auth="Container"
            type="javax.sql.DataSource"
            driverClassName="com.mysql.jdbc.Driver"
            username="root" 
            password=""
            url="jdbc:mysql://localhost:3306/test"
            maxActive="100" 
            maxIdle="30" 
            maxWait="10000"/>
</Context>

In the servlet:

@WebServlet(urlPatterns = { "/" }, loadOnStartup = 0)
public class TestServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    @Resource(name = "jdbc/test")
    private DataSource ds;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
            throws ServletException, IOException {
        resp.setContentType("text/plain");
        try (Connection conn = ds.getConnection(); 
             PrintWriter out = resp.getWriter();) {
            out.println(conn.getMetaData().getDatabaseProductName());
            out.println(conn.getMetaData().getDatabaseProductVersion());
        } catch (SQLException e) {
            log(e.getMessage(), e);
        }
    }

}

The WAR structure is as following:

C:.
+---META-INF
|       context.xml
|       MANIFEST.MF
|
\---WEB-INF
    +---classes
    |   \---test
    |           TestServlet.class
    |
    \---lib
            mysql.jar

The output for this in browser http://localhost:8080/Test/:

MySQL
5.5.32

Upvotes: 4

Ash
Ash

Reputation: 128

Seems this works as is. I was having problems in making this work because of my context not refreshing properly. After redeploying, the ResourceLink was setup properly in the context and the webapp was able to do a JNDI lookup and connect to the datasource.

Upvotes: 0

Related Questions