Connect to Datasource without resource-ref in web.xml

丶灬走出姿态 提交于 2019-12-24 21:42:31

问题


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)


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/18004735/connect-to-datasource-without-resource-ref-in-web-xml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!