Code where I tried to make connection:
DataSource ds = (DataSource)servlet.getServletContext().getAttribute("dbSource");
System.out.println("ds1 : "+ds);
try
{
Connection conn = (Connection) ds.getConnection();
target=login(userName, password,request,conn);
}
catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
And <data-source>
from Struts-Config.xml.
<data-source type="com.mysql.jdbc.jdbc2.optional.MysqlDataSource" key="dbSource" >
<set-property property="driverClassName" value="com.mysql.jdbc.Driver" />
<set-property property="url" value="jdbc:mysql://192.168.10.57:3306/stocks" />
<set-property property="user" value="admin" />
<set-property property="password" value="admin" />
<set-property property="defaultAutoCommit" value="true"开发者_开发技巧 />
<set-property property="defaultReadOnly" value="false" />
<set-property property="maxActive" value="10" />
<set-property property="maxWait" value="5000" />
</data-source>
You don't get the datasource from ServletContext
.
If you defined your datasource in struts-config.xml
(note the letter casing, all in lowercase), then inside your Action
you would get your datasource by calling the getDataSource(HttpServletRequest request)
or getDataSource(HttpServletRequest request, String key)
method.
Example:
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);
}
}
}
Read the Struts 1.x documentation that explains how to declare & retrieve the datasource through Struts.
精彩评论