如何在网页中显示数据库中的数据?

发布于 2024-09-15 23:10:16 字数 9547 浏览 10 评论 0原文

在过去的三天里,我一直在尝试开发一个基于 Web 的 CRUD 应用程序,它可以执行所有 CRUD 操作。考虑到代码的复杂性,我决定先显示数据,然后才能继续进行进一步的 CRUD 操作。

对于这个应用程序,我在这里发布了几个问题。从我的答案到现在为止。

这是我的完整源代码。它没有显示任何错误。但我无法获得输出。

我的服务器端代码中有两个类。对我来说,它看起来不错。但它需要更多的东西才能活跃起来。这是一个很棒的论坛,请告诉我,我该如何克服这个问题。

1) EmpApp.java 只需考虑 getAllEmployee() 方法,忽略其余的。

 package test;
 import java.sql.Connection;
 import java.sql.DriverManager;
 import java.sql.ResultSet;
 import java.sql.SQLException;
 import java.sql.Statement;
 import java.util.Collection;
 import java.util.HashSet;
 import java.util.Set;
 import com.mysql.jdbc.PreparedStatement;
 public abstract class EmpApp implements Set<Employee>
{
public Set<EmpApp> empobj = new HashSet<EmpApp>();
private Set<Employee> persons = new HashSet<Employee>();

public boolean add(Employee employee) {
    return persons.add(employee);
  }

public EmpApp(){

}

public Set<EmpApp> getAllEmp()
{
    return empobj;
}
public void addEmployee(Employee employee) throws SQLException, ClassNotFoundException
{
    int tempID = employee.getId();
    String tname = employee.getName();
    int tage = employee.getAge();
    String tdept = employee.getDept();
    PreparedStatement pstmt;
    Class.forName("com.mysql.jdbc.Driver");
    String url ="jdbc:mysql://localhost:3306/general";
    Connection con = DriverManager.getConnection(url,"root", "1234");
    System.out.println("URL: " + url);
    System.out.println("Connection: " + con);
    pstmt = (PreparedStatement) con.prepareStatement("INSERT INTO PERSON SET ID=?, NAME=?, AGE=?, DEPT=?");
    pstmt.setInt(1, tempID);
    pstmt.setString(2, tname);
    pstmt.setInt(3, tempID);
    pstmt.setString(4, tdept);
    pstmt.executeUpdate();
}

public void updateEmployee(Employee employee) throws SQLException, ClassNotFoundException
{
    int tempID = employee.getId();
    String tname = employee.getName();
    int tage = employee.getAge();
    String tdept = employee.getDept();
    PreparedStatement pstmt;
    Class.forName("com.mysql.jdbc.Driver");
    String url ="jdbc:mysql://localhost:3306/general";
    Connection con = DriverManager.getConnection(url,"root", "1234");
    System.out.println("URL: " + url);
    System.out.println("Connection: " + con);
    pstmt = (PreparedStatement) con.createStatement();
    pstmt = (PreparedStatement) con.prepareStatement("UPDATE PERSON SET NAME=?, AGE=?, DEPT=? WHERE ID=?");
    pstmt.setInt(2, tage);
    pstmt.setString(1, tname);
    pstmt.setString(3, tdept);
    pstmt.setInt(4, tempID);
    pstmt.executeUpdate();
}

public void deleteEmployee(Employee employee) throws ClassNotFoundException, SQLException
{
    int eid = employee.getId(); 
    PreparedStatement pstmt;
    Class.forName("com.mysql.jdbc.Driver");
    String url ="jdbc:mysql://localhost:3306/general";
    Connection con = DriverManager.getConnection(url,"root", "1234");
    System.out.println("URL: " + url);
    System.out.println("Connection: " + con);
    pstmt = (PreparedStatement) con.createStatement();
    pstmt = (PreparedStatement) con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
    pstmt.executeUpdate("DELETE FROM PERSON WHERE ID="+eid);

}
@SuppressWarnings("unchecked")
private Set<EmpApp> getAllEmployee() throws ClassNotFoundException, SQLException
{
    Employee employee = new Employee();
    Statement stmt;
    ResultSet rs;
    Class.forName("com.mysql.jdbc.Driver");
    String url ="jdbc:mysql://localhost:3306/general";
    Connection con = DriverManager.getConnection(url,"root", "1234");
    System.out.println("URL: " + url);
    System.out.println("Connection: " + con);
    stmt = con.createStatement();
    stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
    rs = stmt.executeQuery("SELECT * " + "from person ORDER BY ID");
    while(rs.next())
    {
        String name = rs.getString(2);
        employee.setName(name);
        int id = rs.getInt(1);
        employee.setId(id);
        String dept = rs.getString(4);
        employee.setDept(dept);
        int age = rs.getInt(3);
        employee.setAge(age);
        empobj.addAll((Collection<? extends EmpApp>) employee);
    }
    return empobj;
}

 }

2) Employee.java

package test;
public class Employee 
{   
private Set<Employee> employee = new HashSet<Employee>();
public Employee() {
        // TODO Auto-generated constructor stub
}
private String name;
private String dept;
private int age;
private int id;

public int getId(){
    return id;
}

public void setId(int id){
    this.id = id;
}

public String getName(){
    return name;
}

public void setName(String name){
    this.name = Security.escapeHtml(name);;
}

public int getAge(){
    return age;
}

public void setAge(int age){
    this.age = age;
}

public String getDept(){
    return dept;   
}

public void setDept(String dept){
    this.dept = Security.escapeHtml(dept);
}

public boolean equals(Object obj){
    if (obj == null)
    {
        return false;
    }

    if (obj == this)
    {
        return true;
    }

    if (!this.getClass().equals(obj.getClass()))
    {
        return false;
    }

    Employee that = (Employee) obj;

    if (this.id != that.id)
    {
        return false;
    }

    return true;
}
public String toString(){
    return "Employee[id=" + id + ",name=" + name + "]";
}
}

index.html 代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>Employee Data</title>
  <script type='text/javascript' src='dwr/engine.js'> </script> 
  <script type='text/javascript' src='dwr/util.js'> </script> 
  <script type='text/javascript' src='dwr/interface/EmpApp.js'> </script> 
  <script>
  function init() {
  showTable();
}

var empCache = { };
var viewed = -1;

function showTable() {
  EmpApp.getAllEmployee(function(empobj) {
    dwr.util.removeAllRows("EmpRow", { filter:function(tr) {
      return (tr.id != "pattern");
    }});
    var employee, eid;

    for (var i = 0; i < empobj.length; i++) {
      employee = empobj[i];
          eid = empobj.id;
      dwr.util.cloneNode("pattern", { idSuffix:id });
      dwr.util.setValue("ID" + id, employee.id);
      dwr.util.setValue("NAME" + id, employee.name);
      dwr.util.setValue("AGE" + id, employee.age);
      dwr.util.setValue("DEPT" + id, employee.dept);
      $("pattern" + id).style.display = "table-row";
      empCache[id] = employee;
    }
  });
}


</script>
</head>
<body onload="init();">
<div id="tabContents">

  <div id="demoDiv">

    <h3>Employee</h3>
    <table border="1" class="rowed grey">
      <thead>
        <tr>
          <th>ID</th>
          <th>NAME</th>
          <th>AGE</th>
          <th>DEPT</th>
        </tr>
      </thead>
      <tbody id="EmpRow">
        <tr id="pattern" style="display:none;">
        <td>
            <span id="ID">Name</span><br/> 
            <span id="NAME">Name</span><br/> 
            <span id="AGE">Age</span> 
          </td> 
      <td><span id="DEPT">Dept</span></td>
        </tr>
      </tbody>
    </table>
</div>
</body>
</html>

当然是异步 Web 应用程序。我这里用的是DWR。 dwr.xml 文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE dwr PUBLIC  
"-//GetAhead Limited//DTD Direct Web Remoting 2.0//EN"  
"http://getahead.org/dwr/dwr20.dtd">  

<dwr>
  <allow>
    <create creator="new" javascript="EmpApp" scope="script">
      <param name="class" value="test.EmpApp"/>
      <include method="GetAllEmployee"/>
    </create>
    <convert match="test.EmpApp" converter="bean"/>
  </allow>
</dwr>

以及最终的 web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>LastDisplay</display-name>
   <servlet>
    <servlet-name>dwr-invoker</servlet-name>
    <servlet-class>uk.ltd.getahead.dwr.DWRServlet</servlet-class>
    <init-param>
        <param-name>debug</param-name>
        <param-value>true</param-value>
    </init-param>
</servlet>

<servlet-mapping>
    <servlet-name>dwr-invoker</servlet-name>
    <url-pattern>/dwr/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>

For the last three days I have been trying to develop a web based CRUD application which does all the CRUD operations. Given the complexity of the code, I decided to show the data first then I can move on to further CRUD operations.

For this application I posted several questions in here. From the Answers I came this far.

Here is my full source code. It's not showing any errors. But I'm not able to get the output.

I have two class in my server side code. For me, its looks like good. But it needs something more to come alive. This is a great forum, please tell me, how can I overcome this.

1) EmpApp.java
Just consider the getAllEmployee() method, omit the rest.

 package test;
 import java.sql.Connection;
 import java.sql.DriverManager;
 import java.sql.ResultSet;
 import java.sql.SQLException;
 import java.sql.Statement;
 import java.util.Collection;
 import java.util.HashSet;
 import java.util.Set;
 import com.mysql.jdbc.PreparedStatement;
 public abstract class EmpApp implements Set<Employee>
{
public Set<EmpApp> empobj = new HashSet<EmpApp>();
private Set<Employee> persons = new HashSet<Employee>();

public boolean add(Employee employee) {
    return persons.add(employee);
  }

public EmpApp(){

}

public Set<EmpApp> getAllEmp()
{
    return empobj;
}
public void addEmployee(Employee employee) throws SQLException, ClassNotFoundException
{
    int tempID = employee.getId();
    String tname = employee.getName();
    int tage = employee.getAge();
    String tdept = employee.getDept();
    PreparedStatement pstmt;
    Class.forName("com.mysql.jdbc.Driver");
    String url ="jdbc:mysql://localhost:3306/general";
    Connection con = DriverManager.getConnection(url,"root", "1234");
    System.out.println("URL: " + url);
    System.out.println("Connection: " + con);
    pstmt = (PreparedStatement) con.prepareStatement("INSERT INTO PERSON SET ID=?, NAME=?, AGE=?, DEPT=?");
    pstmt.setInt(1, tempID);
    pstmt.setString(2, tname);
    pstmt.setInt(3, tempID);
    pstmt.setString(4, tdept);
    pstmt.executeUpdate();
}

public void updateEmployee(Employee employee) throws SQLException, ClassNotFoundException
{
    int tempID = employee.getId();
    String tname = employee.getName();
    int tage = employee.getAge();
    String tdept = employee.getDept();
    PreparedStatement pstmt;
    Class.forName("com.mysql.jdbc.Driver");
    String url ="jdbc:mysql://localhost:3306/general";
    Connection con = DriverManager.getConnection(url,"root", "1234");
    System.out.println("URL: " + url);
    System.out.println("Connection: " + con);
    pstmt = (PreparedStatement) con.createStatement();
    pstmt = (PreparedStatement) con.prepareStatement("UPDATE PERSON SET NAME=?, AGE=?, DEPT=? WHERE ID=?");
    pstmt.setInt(2, tage);
    pstmt.setString(1, tname);
    pstmt.setString(3, tdept);
    pstmt.setInt(4, tempID);
    pstmt.executeUpdate();
}

public void deleteEmployee(Employee employee) throws ClassNotFoundException, SQLException
{
    int eid = employee.getId(); 
    PreparedStatement pstmt;
    Class.forName("com.mysql.jdbc.Driver");
    String url ="jdbc:mysql://localhost:3306/general";
    Connection con = DriverManager.getConnection(url,"root", "1234");
    System.out.println("URL: " + url);
    System.out.println("Connection: " + con);
    pstmt = (PreparedStatement) con.createStatement();
    pstmt = (PreparedStatement) con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
    pstmt.executeUpdate("DELETE FROM PERSON WHERE ID="+eid);

}
@SuppressWarnings("unchecked")
private Set<EmpApp> getAllEmployee() throws ClassNotFoundException, SQLException
{
    Employee employee = new Employee();
    Statement stmt;
    ResultSet rs;
    Class.forName("com.mysql.jdbc.Driver");
    String url ="jdbc:mysql://localhost:3306/general";
    Connection con = DriverManager.getConnection(url,"root", "1234");
    System.out.println("URL: " + url);
    System.out.println("Connection: " + con);
    stmt = con.createStatement();
    stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
    rs = stmt.executeQuery("SELECT * " + "from person ORDER BY ID");
    while(rs.next())
    {
        String name = rs.getString(2);
        employee.setName(name);
        int id = rs.getInt(1);
        employee.setId(id);
        String dept = rs.getString(4);
        employee.setDept(dept);
        int age = rs.getInt(3);
        employee.setAge(age);
        empobj.addAll((Collection<? extends EmpApp>) employee);
    }
    return empobj;
}

 }

2) Employee.java

package test;
public class Employee 
{   
private Set<Employee> employee = new HashSet<Employee>();
public Employee() {
        // TODO Auto-generated constructor stub
}
private String name;
private String dept;
private int age;
private int id;

public int getId(){
    return id;
}

public void setId(int id){
    this.id = id;
}

public String getName(){
    return name;
}

public void setName(String name){
    this.name = Security.escapeHtml(name);;
}

public int getAge(){
    return age;
}

public void setAge(int age){
    this.age = age;
}

public String getDept(){
    return dept;   
}

public void setDept(String dept){
    this.dept = Security.escapeHtml(dept);
}

public boolean equals(Object obj){
    if (obj == null)
    {
        return false;
    }

    if (obj == this)
    {
        return true;
    }

    if (!this.getClass().equals(obj.getClass()))
    {
        return false;
    }

    Employee that = (Employee) obj;

    if (this.id != that.id)
    {
        return false;
    }

    return true;
}
public String toString(){
    return "Employee[id=" + id + ",name=" + name + "]";
}
}

The index.html code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>Employee Data</title>
  <script type='text/javascript' src='dwr/engine.js'> </script> 
  <script type='text/javascript' src='dwr/util.js'> </script> 
  <script type='text/javascript' src='dwr/interface/EmpApp.js'> </script> 
  <script>
  function init() {
  showTable();
}

var empCache = { };
var viewed = -1;

function showTable() {
  EmpApp.getAllEmployee(function(empobj) {
    dwr.util.removeAllRows("EmpRow", { filter:function(tr) {
      return (tr.id != "pattern");
    }});
    var employee, eid;

    for (var i = 0; i < empobj.length; i++) {
      employee = empobj[i];
          eid = empobj.id;
      dwr.util.cloneNode("pattern", { idSuffix:id });
      dwr.util.setValue("ID" + id, employee.id);
      dwr.util.setValue("NAME" + id, employee.name);
      dwr.util.setValue("AGE" + id, employee.age);
      dwr.util.setValue("DEPT" + id, employee.dept);
      $("pattern" + id).style.display = "table-row";
      empCache[id] = employee;
    }
  });
}


</script>
</head>
<body onload="init();">
<div id="tabContents">

  <div id="demoDiv">

    <h3>Employee</h3>
    <table border="1" class="rowed grey">
      <thead>
        <tr>
          <th>ID</th>
          <th>NAME</th>
          <th>AGE</th>
          <th>DEPT</th>
        </tr>
      </thead>
      <tbody id="EmpRow">
        <tr id="pattern" style="display:none;">
        <td>
            <span id="ID">Name</span><br/> 
            <span id="NAME">Name</span><br/> 
            <span id="AGE">Age</span> 
          </td> 
      <td><span id="DEPT">Dept</span></td>
        </tr>
      </tbody>
    </table>
</div>
</body>
</html>

Of course its Asynchronous web application. I am using DWR here.
The dwr.xml file

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE dwr PUBLIC  
"-//GetAhead Limited//DTD Direct Web Remoting 2.0//EN"  
"http://getahead.org/dwr/dwr20.dtd">  

<dwr>
  <allow>
    <create creator="new" javascript="EmpApp" scope="script">
      <param name="class" value="test.EmpApp"/>
      <include method="GetAllEmployee"/>
    </create>
    <convert match="test.EmpApp" converter="bean"/>
  </allow>
</dwr>

And the Final web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>LastDisplay</display-name>
   <servlet>
    <servlet-name>dwr-invoker</servlet-name>
    <servlet-class>uk.ltd.getahead.dwr.DWRServlet</servlet-class>
    <init-param>
        <param-name>debug</param-name>
        <param-value>true</param-value>
    </init-param>
</servlet>

<servlet-mapping>
    <servlet-name>dwr-invoker</servlet-name>
    <url-pattern>/dwr/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

江南月 2024-09-22 23:10:16

看看数据绑定,我从来没有在 Java 中这样做过,但在 .net 中是这样的。

表适配器主要是连接信息和一些存储的sql命令,以便于重复。

TableNameTableAdapter tabAdapt = new TableNameTableAdapter();
this.labelName.DataSource = tabAdapt.GetWorkInformation(input for query);
this.labelName.DataBind();

对于 java,请查找 javax.sql.datasource 以获取更多信息。

look into databinding, I've never done this in Java but in .net its something like this.

the table adapter is mostly what the connection information and some stored sql commands for easy repetition.

TableNameTableAdapter tabAdapt = new TableNameTableAdapter();
this.labelName.DataSource = tabAdapt.GetWorkInformation(input for query);
this.labelName.DataBind();

for java look up javax.sql.datasource for more info.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文