Usar un DataSource directamente con Struts

2000 vistas

Para usar un datasource declarado en el fichero struts-config.xml, por ejemplo en una Action, tendremos que hacer como sigue:



java
  1. public ActionForward  execute(ActionMapping mapping,
  2.                                     ActionForm form,
  3.                                     HttpServletRequest request,
  4.                                     HttpServletResponse response) throws Exception
  5. {
  6. javax.sql.DataSource dataSource;
  7. java.sql.Connection myConnection;
  8. try
  9. {
  10.   dataSource = getDataSource(request);
  11.   myConnection = dataSource.getConnection();
  12.   // hacer aquà el tratamiento a partir de la conexión.
  13. }
  14. catch (SQLException sqle)
  15. {
  16.     ...
  17. }
  18. finally
  19. {
  20.     try {
  21.       myConnection.close();
  22.     } catch (SQLException e) {
  23.       getServlet().log("Connection.close", e);
  24.     }
  25.   }
  26. }