<struts-config>是Struts配置文件的根元素,和它对应的配置类为org.apache.struts.config.ModuleConfig。它的DTD定义如下:<!ELEMENT struts-config(data-sources?,form-beans?,global-exceptions?,global-forwards?,action-mappings?,controller?,message-resources*,plugin-in*)。在Struts配置文件中,必须按以上DTD指定的先后顺序来配置<struts-config>元素的各个子元素。
一、<data-sources>元素: <data-sources>可包括多个<data-source>元素,<data-source>元素配置形式如下:
<data-source type="org.apache.commons.dbcp.BasicDataSource"> <set-property property="autoCommit" value="true"/>
<set-property property="driverClass" value="......"/>
<set-property property="url" value="......"/>
<set-property property="maxCount" value="10"/>
<set-property property="minCount" value="2"/>
<set-property property="user" value="....."/>
<set-property property="password" value="......"/>
</data-source>
配置了数据源后,可以通过以下代码访问数据源:
public ActionForward
execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception
{
javax.sql.DataSource dataSource;
java.sql.Connection myConnection;
try {
dataSource = getDataSource(request);
myConnection = dataSource.getConnection();
// do what you wish with myConnection
} catch (SQLException sqle) {
getServlet().log("Connection.process", sqle);
} finally {
//enclose this in a finally block to make
//sure the connection is closed
try {
myConnection.close();
} catch (SQLException e) {
getServlet().log("Connection.close", e);
}
}
}
当在配置文件中声明多个数据源时,此时需要为每一个数据源分配一个唯一的key 值,通过该值来访问特定的数据源。例如:
data-sources>
<data-source key="A" type="org.apache.commons.dbcp.BasicDataSource">
... properties as before ...
</data-source>
<data-source key="B" type="org.apache.commons.dbcp.BasicDataSource">
... properties as before ...
</data-source>
...
</data-sources>
此时可通过如下代码访问数据源:
dataSourceA = getDataSource(request, "A");
dataSourceB = getDataSource(request, "B");