“ Netbean中的Java EE企业应用程序”。 Servlet和JSP无法连接到数据库

时间:2019-03-11 16:57:46

标签: java jsp servlets java-ee netbeans-8

我是新手程序员。谁能看看我的代码,看看有什么问题吗?我的jsp文件(studentList.jsp)没有显示出我所期望的Error Image(应该显示从Servlet的数据库中读取的学生列表)。

我的项目在Netbean的Jave EE / Enterprise Application上运行。该Web应用程序在本地主机上运行。数据库是Java Derby。

我想我没有通过Servlet正确连接到数据库。我在这里显示所有代码。我希望您阅读的时间不会太长。如果有人认为它太长,那么请至少只看两个类的代码:student.jsp和Servlet。我认为问题可能出在这里。

我尝试看了很多教程,但在这种情况下无济于事。请帮我。 预先非常感谢。

学生班

package StudentDB;
public class Student {
    public static int studentNumber=0;
    private int StID;
    private String firstName;
    private String lastName;

    public Student(int studentID, String firstName, String lastName) {
        this.StID = studentID;
        if (StID>studentNumber)
        {
            studentNumber= StID;
        }
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public Student(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
        studentNumber++;
        this.setStudentID(studentNumber);
    }



    @Override
    public String toString() {
        return "Student{" + "studentID=" + StID + ", firstName=" + firstName + ", lastName=" + lastName + '}';
    }

    //get and set method
    public int getStudentID() {
        return StID;
    }

    public void setStudentID(int studentID) {
        this.StID = studentID;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public static int getStudentNumber() {
        return studentNumber;
    }

    public static void setStudentNumber(int studentNumber) {
        Student.studentNumber = studentNumber;
    }


}

StudentBean类

package StudentDB;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import javax.activation.DataSource;
import javax.ejb.Stateless;
import javax.ejb.LocalBean;

@Stateless
@LocalBean
public class StudentBean {

    private ArrayList<Student> StudentList;
    // The driverURL to contain the Database Driver
      private final String driverURL = "org.apache.derby.jdbc.EmbeddedDriver";
    // The dbURL to contain the Database URL
      private final String dbURL = "jdbc:derby://localhost:1527/DMSDB;" + 
                "create=true;user=dms;password=dms2018";
      private final String tableName="DITMEMAY";

    public StudentBean() throws SQLException, ClassNotFoundException
    {
        //Create StudentList
        StudentList= new ArrayList<Student>();
        //Create Connection
        Connection connection= connectDatabaseSchema();
        // Creating the SQL Statement
        Statement statement = connection.createStatement();
        //if connect sucessfully

        //if studentDB table exist 
        if (isTableExisting(tableName,connection))
        {
            System.out.println("table existed");
            //Reading records from Student Table
            ResultSet rs=statement.executeQuery("SELECT * FROM "+tableName);

            while(rs.next())
            {
                int studentID= rs.getInt("StID"); //read studentID
                String firstName= rs.getString("firstName"); //read student first Name
                String lastName= rs.getString("lastName");// read student last Name
                //create Student Object
                Student aStudent= new Student(studentID, firstName, lastName);
                //add Student to studentList
                StudentList.add(aStudent);
                System.out.println("one student has been added");
            }               
        }
        else //if studentDB table not exist
        {
             System.out.println("table is not existed");
            // Step 4: Creating a new STUDENTDB table in DMSDB
            String sqlQuery = "CREATE TABLE "+tableName + " (StID INT PRIMARY KEY," +
            " firstName VARCHAR(20), lastName VARCHAR(20))";
            int resultDB = statement.executeUpdate(sqlQuery);
            if(resultDB == 0)
            System.out.println("Student Table is created");
            // Step 5: Inserting a record in the Student table in DMSDB
            sqlQuery = "INSERT INTO "+ tableName +" VALUES" +
            "(1, 'Bob', 'Nilson')," +
            "(2, 'Nicholas', 'Jose')," +
            "(3, 'Minh', 'Nguyen')," +
            "(4, 'Zetting', 'Luo'),"+
            "(5, 'Michal', 'Kovac'),"+
            "(6, 'Karoline', 'Wang')";
            resultDB = statement.executeUpdate(sqlQuery);
            if(resultDB == 6)
            System.out.println("6 records are insterted in Student Table");
            //add data
            initialiseStudentList();
        }
         //close connection
        connection.close();
    }


    // Add business logic below. (Right-click in editor and choose
    // "Insert Code > Add Business Method")
    public void addStudent(Student aStudent) throws ClassNotFoundException, SQLException {
        this.StudentList.add(aStudent);
         //Create Connection
        Connection connection= connectDatabaseSchema();
        // Creating the SQL Statement
        Statement statement = connection.createStatement();
        String sqlQuery = "INSERT INTO "+ tableName +" VALUES (" + 
                aStudent.getStudentID()+" ,'"+aStudent.getFirstName()+"','"+aStudent.getLastName()+"')";
        statement.executeUpdate(sqlQuery);
        System.out.println("Student has been added");
        //close connection
        connection.close();
    }

    public void removeStudent(Student aStudent) throws ClassNotFoundException, SQLException
    {
        this.StudentList.remove(aStudent);
         //Create Connection
        Connection connection= connectDatabaseSchema();
        // Creating the SQL Statement
        Statement statement = connection.createStatement();
        String sqlQuery = "DELETE FROM "+ tableName +" WHERE StID="+aStudent.getStudentID();
        statement.executeUpdate(sqlQuery);
        System.out.println("Student has been removed");
        //close connection
        connection.close();
    }

    public Student retrieveStudentInformation(int studentID) throws ClassNotFoundException, SQLException
    {
        //Create Connection
        Connection connection= connectDatabaseSchema();
        // Creating the SQL Statement
        Statement statement = connection.createStatement();
        String sqlQuery = "SELECT * FROM "+tableName+" WHERE StID="+studentID;
        ResultSet resultSet = statement.executeQuery(sqlQuery);
        // Step 7: Reading data from the ResultSet
        while(resultSet.next()){
            System.out.println(resultSet.getString(1) + "\t"
                    + resultSet.getString(2) + "\t"
                    + resultSet.getString(3));
        }
        //close connection
        connection.close();
        return null;
    }

    //this method is to check if the table Student already exist in the database
     private static boolean isTableExisting(String tableName, Connection theConnection) throws SQLException
    {
        DatabaseMetaData theMetaData = theConnection.getMetaData();

        ResultSet existingTable = theMetaData.getTables(null, null, tableName.toUpperCase(), null);

        if(existingTable.next())
        {
                return true;
        }
        return false;
    }

     private Connection connectDatabaseSchema() throws ClassNotFoundException, SQLException
     {

            // Step 1: Loading the drivers for JAVA DB
            Class.forName(driverURL);
            // Network Driver both will work with this example.
            // You can use any one of them
            //Class.forName("org.apache.derby.jdbc.ClientDriver");

            // Step 2: Connecting to sample Database in Java DB
            Connection connection = DriverManager.getConnection(dbURL);
            System.out.println("Database is connected...");
            return connection;
     }

     private void initialiseStudentList()
     {
         StudentList.add(new Student(1, "Bob", "Nilson"));
         StudentList.add(new Student(2, "Nicholas", "Jose"));
         StudentList.add(new Student(3, "Minh", "Nguyen"));
         StudentList.add(new Student(4, "Zetting", "Luo"));
         StudentList.add(new Student(5, "Michal", "Kovac"));
         StudentList.add(new Student(6, "Karoline", "Wang"));
     }

     //getter and setter
    public ArrayList<Student> getStudentList() {
        return StudentList;
    }

    public void setStudentList(ArrayList<Student> StudentList) {
        this.StudentList = StudentList;
    }
}

Servlet

import StudentDB.Student;
import StudentDB.StudentBean;
import java.io.IOException;
import java.util.ArrayList;
import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class StudentDBServlet extends HttpServlet {
@EJB
private StudentBean studentBean;


@Override
public void init() throws ServletException {
    super.init(); //To change body of generated methods, choose Tools | Templates.
    try
    {
        studentBean= new StudentBean();
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        getStudentListDB(request, response);
}


@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    doGet(request,response);
}

private void getStudentListDB(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //get StudentList from DB
    ArrayList<Student> studentList= studentBean.getStudentList();
    //add StudentList to request
    request.setAttribute("STUDENT_LIST", studentList);
    //send to JSP page
    RequestDispatcher dispatcher= request.getRequestDispatcher("/studentList.jsp");
    dispatcher.forward(request, response);
}

}

studentList.jsp

<%@page import="java.util.ArrayList"%>
<%@page import="StudentDB.Student"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Student List</title>
    </head>
    <% ArrayList<Student> studentList= (ArrayList<Student>)request.getAttribute("STUDENT_LIST");%>
    <body>
        <h2>LIST STUDENTS</h2>
        <div>
            <table>
                <tr>
                    <th>Student ID</th>
                    <th>First Name</th>
                    <th>Last Name</th>
                </tr>

                <% for (Student aStudent: studentList) {%>
                <tr>
                    <td> <%= aStudent.getStudentID()%> </td>
                    <td> <%= aStudent.getFirstName() %> </td>
                    <td> <%= aStudent.getLastName() %> </td>
                </tr>
                <%}%>

            </table>
        </div>

    </body>
</html>

0 个答案:

没有答案