Notes for configuring data-source in the struts-config.xml:
<Data-sources>
<! --
Name: data-source
Description: The data-source element defines specific data source attributes:
@ Key: when multiple data sources need to be configured, it is equivalent to the data source name, which is used to differentiate data sources from each other.
@ Type: Class implemented by the data source that can be used, generally from the following four libraries
-->
<Data-source key = "dataSource" type = "org. apache. commons. dbcp. BasicDataSource">
<! --
Name: set-property:
@ DriverClassName: Driver name
@ Url: Database url
@ User: Database user
@ Password: Database password
@ MaxCount: Maximum number of data source connections
@ MinCount: Minimum number of data source connections
@ AutoCommit: whether to submit automatically. Optional values: true/false.
@ Description: data source description
@ ReadOnly: the read-only attribute must be set to false. Otherwise, you cannot insert or modify the attribute.
-->
<Set-property = "driverClassName"
Value = "Oracle. jdbc. driver. OracleDriver"/>
<Set-property = "url"
Value = "jdbc: oracle: thin: @ localhost: 1521: orcl"/>
<Set-property = "username" value = "scott"/>
<Set-property = "password" value = "tiger"/>
<Set-property = "maxCount" value = "20"/>
<Set-property = "minCount" value = "5"/>
<Set-property = "autoCommit" value = "true"/>
<Set-property = "readOnly" value = "false"/>
<Set-property = "description" value = "ds"/>
</Data-source>
</Data-sources>
Code in the ** DAO file:
First define
Private DataSource;
Constructor of this class:
Public ** DAO (DataSource dataSource)
{
This. dataSource = dataSource;
}
Then, use dataSource. getConnection () to obtain the connection in the method of this class.
Be sure not to use static methods
There are two methods to call the configured datasource in the action class:
Method 1: ServletContext context = servlet. getServletContext (); // obtain the attributes of the configuration file in Struts
DataSource dataSource = (DataSource) context. getAttribute ("dataSource ");
Method 2: DataSource ds = this. getDataSource (request, "dataSource ");
** DAO ** dao = new ** DAO (ds );
The getDataSource (HttpServletRequest request, String key) method is to call the configured data-source in the action.
Of course, the parameter key in the method is the key of the <data-source> you configured
The comparison method 2 is concise! It took a lot of effort to get it out ·····