我試圖從一個數據庫中的表中打印所有元素,使用JSP進行賦值,但要求是從後端獲取元素。 (JSP CRUD操作工作得很好)。問題是我得到一張空桌子。這裏是我的代碼:JSTL - 從java中獲取對象
JSP:
<html>
<head>
<title>SELECT Operation</title>
</head>
<body>
<c:set var="students" scope="session" value="${StudentDaoImpl.allStudents}"/>
<table border="1" width="100%">
<tr>
<th>Student ID</th>
<th>Name</th>
</tr>
<c:forEach var="student" items="${students}">
<tr>
<td><c:out value="${student.ID}"/></td>
<td><c:out value="${student.Name}"/></td>
</tr>
</c:forEach>
</table>
</body>
</html>
StudentDaoImpl類:
public class StudentDaoImpl implements StudentDao{
private Connection connection;
public StudentDaoImpl(){
Properties connectionProps = new Properties();
connectionProps.put("user", "root");
connectionProps.put("password", "password");
try {
connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test",connectionProps);
System.out.println("Connection to MySql successful.");
} catch (Exception e) {
System.out.println("Could not connect to MySql.");
e.printStackTrace();
}
}
@Override
public List<Student> getAllStudents(){
StudentDaoImpl DAO = new StudentDaoImpl();
return DAO.executeQuery("SELECT * FROM students");
}
private List<Student> executeQuery(String sqlQuery){
List<Student> students = new LinkedList<>();
try {
Statement statement = this.connection.createStatement();
ResultSet resultSet = statement.executeQuery(sqlQuery);
while(resultSet.next()){
Student currentStudent = new Student();
currentStudent.setID(resultSet.getInt("ID"));
currentStudent.setName(resultSet.getString("NAME"));
students.add(currentStudent);
}
} catch (Exception e) {
e.printStackTrace();
}
return students;
}
}
和學生類:
public class Student {
private int id;
private String name;
public Student(){
}
public void setID(int newID){
this.id = newID;
}
public int getID(){
return this.id;
}
public void setName(String newName){
this.name = newName;
}
public String getName(){
return this.name;
}
}
如果我直接從JSP訪問數據庫,一切都是好的,但如果我以這種方式嘗試,我所得到的只是表頭。
此外,StudentDaoImpl類正常工作,只使用java並將結果打印到標準輸出,所以肯定這是一個通信問題。
我正在使用Netbeans。我也得到這個運行時間:
Running war on http://localhost:8080/JSPwithJDBC
Using existing Tomcat server configuration at D:\NetBeans 8.0.2\Projects\JSPwithJDBC\target\tomcat
Feb 08, 2015 3:16:13 AM org.apache.catalina.startup.Embedded start
INFO: Starting tomcat server
Feb 08, 2015 3:16:13 AM org.apache.catalina.core.StandardEngine start
INFO: Starting Servlet Engine: Apache Tomcat/6.0.29
Feb 08, 2015 3:16:14 AM org.apache.coyote.http11.Http11Protocol init
INFO: Initializing Coyote HTTP/1.1 on http-8080
Feb 08, 2015 3:16:14 AM org.apache.coyote.http11.Http11Protocol start
INFO: Starting Coyote HTTP/1.1 on http-8080
看來它運行的是tomcat 6,即使我已經安裝了tomcat 8。我讀過tomcat 6有問題,有沒有什麼辦法可以強制它在tomcat 8上運行?
任何幫助,非常感謝!