2013-08-01 30 views
0

我有一個運行在tomcat7上的web應用程序。 tomcat7和全局數據源配置組件是jetty入口的一部分。現在,我可以在門戶網站上設置全局數據源,將其作爲ResourceLink添加到context.xml(我的應用程序在tomcat上)。我想知道是否有一種方法可以通過我的應用程序jdbc代碼連接到這些數據源,而無需在我的web.xml中輸入resource-ref。無需資源ref在web.xml中連接到數據源

(這將幫助我連接到新的數據源名稱,而不重新部署我的WAR文件只是爲了添加新的資源引用標籤)

回答

0

看來這可以作爲是。由於我的上下文沒有正確刷新,因此在開展此項工作時遇到了問題。 重新部署後,ResourceLink在上下文中正確設置,webapp能夠執行JNDI查找並連接到數據源。

2

如果您使用Apache Tomcat 7,則可以在servlet中使用@Resource來注入數據源。

添加在META-INF目錄中的文件context.xml,本地的項目:

<?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> 

在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); 
     } 
    } 

} 

的WAR結構如下:

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

這在瀏覽器http://localhost:8080/Test/的輸出:

MySQL 
5.5.32