我试图从一个数据库中的表中打印所有元素,使用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上运行?
任何帮助,非常感谢!