开发者

Unable to use DataSource in struts 1.3.10

开发者 https://www.devze.com 2023-02-19 05:16 出处:网络
Code where I tried to make connection: DataSource ds = (DataSource)servlet.getServletContext().getAttribute(\"dbSource\");

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消