Codice completo

Listato 2. LookupAction per utilizzare il DataSource

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.struts.action.*;
import java.sql.*;
import javax.sql.*;

public class LookupAction extends Action {

  /*
  protected Double getQuote(String symbol) {

    if (symbol.equalsIgnoreCase("SUNW")) {
      return new Double(25.00);
    }

    return null;
  }
  */

  protected Double getQuote(HttpServletRequest request, String symbol) {

    Double price = null;
    Connection conn = null;
    Statement stmt = null;
    ResultSet rs = null;
    DataSource dataSource = null;

    try {

      dataSource = getDataSource(request);
      conn = dataSource.getConnection();
      stmt = conn.createStatement();
      rs = stmt.executeQuery("SELECT * FROM Stocks WHERE symbol='" + symbol + "'");
      
      if (rs.next()) {
    
        double tmp = rs.getDouble("price");
        price = new Double(tmp);
        System.err.println("price: " + price);
      } else {
        System.err.println("Symbol not found returning null");
      }
    } catch (SQLException sqle) {

      System.err.println(sqle.getMessage());

    } finally {
      try {
      rs.close();
      stmt.close();
      conn.close();      
      } catch (Exception e) {
        System.err.println(e.getMessage());
      }
    }

    return price;
  }

  public ActionForward execute(ActionMapping mapping,
    ActionForm form,
    HttpServletRequest request,
    HttpServletResponse response)
  throws IOException, ServletException {
  
    Double price = null;

    String target = "success";

    if (form!=null) {
      LookupForm lookupForm = (LookupForm) form;
      
      String symbol = lookupForm.getSymbol();
      price = getQuote(request, symbol);
    }

    if (price==null) {
      target = new String("failure");
    } else {
      request.setAttribute("PRICE", price);
    }

    return (mapping.findForward(target));
  }
}