2011-05-25 68 views
1

我正在使用MySQL在我的GWT應用程序中建立數據庫連接。我希望數據庫讀取一組'init'參數,以便我不需要'手動編寫'DB URL和用戶名和密碼。 我搜索了一段時間尋找可能的解決方案,但卻被可能的解決方案所困惑。他們中的一些人談到了JNDI的解決方案,但沒有明確說明如何去做。GWT中用於數據庫連接的初始化參數

此外,在Eclipse中以開發/調試模式(在Jetty中)運行應用程序並將其部署到Tomcat中的差異進一步使我感到困惑。

是否可以在web.xml中指定一組初始化參數?我如何閱讀他們?

如果要使用JNDI?我可以逐步簡明地總結如何實現此任務?

回答

1

你所尋找的是Web應用程序上下文設置 -

要添加Web應用程序上下文中的數據庫信息

要配置碼頭,您將不得不使用jetty-web.xml配置 -

要做到在您的應用程序的連接,在服務器端使用下列 -

 Context ctx = new InitialContext(); 

     DataSource ds = (DataSource) ctx.lookup("java:comp/env/{Res Name in context.xml}"); 
     Connection conn = ds.getConnection(); 

注意 - 要使您的應用程序都與jetty和tomcat一起運行,請同時使用這兩個文件並確保您的資源名稱是 -

context.xml : {resourceName}

jetty-web.xml: java:comp/env/{resourceName}

不知道碼頭-web.xml將只有{}資源名稱工作太

編輯 - 樣的context.xml代碼 -

<Resource name="jdbc/myDatabaseServer" auth="Container" type="javax.sql.DataSource" 
    maxActive="100" maxIdle="30" maxWait="10000" username="USER" 
    password="PWD" driverClassName="com.mysql.jdbc.Driver" 
    url="jdbc:mysql://myUrl:3306/myDB?autoReconnect=true" removeAbandoned="true" 
    removeAbandonedTimeout="60" logAbandoned="true" autoReconnect="true" validationQuery="select 1" testOnBorrow="true" 
    testOnReturn="true" testWhileIdle="true" timeBetweenEvictionRunsMillis="1800000" 
    numTestsPerEvictionRun="3" minEvictableIdleTimeMillis="1800000"/> 

同一樣本jetty-web.xml代碼 -

<New id="someid" class="org.mortbay.jetty.plus.naming.Resource"> 
    <Arg>java:comp/env/jdbc/myDatabaseServer</Arg> 
    <Arg> 
     <New class="org.apache.commons.dbcp.BasicDataSource"> 
      <Set name="driverClassName">com.mysql.jdbc.Driver</Set> 
      <Set name="url">jdbc:mysql://myUrl:3306/myDB?autoReconnect=true</Set> 
      <Set name="username">USER</Set> 
      <Set name="password">PWD</Set> 
      <Set name="maxActive">100</Set> 
      <Set name="maxIdle">30</Set> 
      <Set name="minIdle">0</Set> 
      <Set name="maxWait">10000</Set> 
      <Set name="minEvictableIdleTimeMillis">1800000</Set> 
      <Set name="timeBetweenEvictionRunsMillis">1800000</Set> 
      <Set name="numTestsPerEvictionRun">3</Set> 
      <Set name="testOnBorrow">true</Set> 
      <Set name="testWhileIdle">true</Set> 
      <Set name="testOnReturn">true</Set> 
      <Set name="validationQuery">SELECT 1</Set> 
     </New> 
    </Arg> 
</New> 

你可以閱讀每節的含義。

+0

我在執行此操作時遇到錯誤503「服務不可用」錯誤。可能的原因是什麼? – 2011-05-26 05:27:11

+0

我正在關注此資源,因爲它是 - > http://humblecode.blogspot.com/2009/05/gwt-16-using-jndi-datasource.html – 2011-05-26 05:47:01

+0

謝謝!我解決了這個問題。:) – 2011-05-26 06:51:02