如何将SQL查询结果发送到jsp页面?

1 jsp jdbc

我有一个包含 id(number)、name(string)、address(string) 字段的数据库。

我写了一个java程序EmployeeDAO来执行查询。我将它存储在一个 ResultSet 对象中rs。我需要将此结果集显示为 JSP 页面中的表格。我如何将它发送rs到 JSP 页面?

public class EmployeeDAO 
{
    public _____ list() throws Exception
    {
        try
        {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
            String url = "jdbc:odbc:employee_dsn";
            Connection con = DriverManager.getConnection(url);
            Statement stmt = con.createStatement();
            ResultSet rs = stmt.executeQuery("Select * from emp_table");
        }
            catch (Exception e)
        {   
             System.out.println(e);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Bor*_*vić 5

首先创建具有与 emp_table 中的列相同的字段的 Java 模型类 Employee。例如:

public class Employee {
  private String name;
  private String lastName;
  public void setName(String name) {
    this.name = name;
  }
  public String getName() {
    return this.name;
  }
  public String getLastName() {
    return this.lastName;
  }
  public void setLastName(String lastName) {
    this.lastName = lastName;
  }
}
Run Code Online (Sandbox Code Playgroud)

然后在您的方法 _list() 中迭代结果集,如下所示:

public List<Employee> _ list() throws Exception {
     Connection con = null;
     ResultSet rs = null;
     List<Employee> result = new ArrayList<Employee>();
     try
       {
         Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
         String url = "jdbc:odbc:employee_dsn";
         con = DriverManager.getConnection(url);
         Statement stmt = con.createStatement();
         rs = stmt.executeQuery("Select * from emp_table");
         while (rs.next()) {
           Employee emp = new Employee();
          emp.setName(rs.getString("emp_name"));
          emp.setLastName(rs.getString("emp_last_name"));
          result.add(emp);
         }

        }
        catch (Exception e)
        {       
            System.out.println(e);
        } finally {
            if (null != rs) {
              try { rs.close()} catch(Exception ex) {};
            }
            if (null != con) {
              try { con.close()} catch(Exception ex) {};
            }
        }
return result;
  }
Run Code Online (Sandbox Code Playgroud)

在您的 JSP 中,您可以像这样遍历集合:

<table>
  <c:forEach var="emp" items="${empDao._list}">
    <tr>
      <td>${emp.name}</td>
      <td>${emp.lastName}</td>
    </tr>
  </c:forEach>
</table>
Run Code Online (Sandbox Code Playgroud)