如何使用 Java servlet、Hibernate、JSP 从数据库检索数据?帮助我:)
文件StudentModel.java
public class StudentModel {
private final SessionFactory sf = HibernateUtil.getSessionFactory();
public List<Student> studentList()
{
try{
sf.getCurrentSession().beginTransaction();
List<Student> result = sf.getCurrentSession().createCriteria(Student.class).list();
return result;
}
catch(Exception e)
{
return null;
}
}
}
文件Index.jsp
<body>
<% StudentModel sm = new StudentModel();%>
<c:forEach var ="student" items="<%= sm.studentList()%>">
Id: ${student.Id}<br>
name:${student.Name}
</c:foreach>
</body>
文件Student.hbm.xml(文件配置映射到数据库中的属性)
<hibernate-mapping>
<class name="entities.Student" table="Student" schema="dbo" catalog="javaTest">
<id name="id" type="int">
<column name="Id" />
<generator class="identity" />
</id>
<property name="name" type="string">
<column name="Name" length="100" />
</property>
</class>
最佳答案
将学生列表保存为 servlet 中的请求对象,如下所示:
public void doPost(HttpServletRequest req, HttpServletResponse resp) {
List<Student> students = new StudentModel().studentList();
req.setAttribute("students", students);
}
然后在您的 jsp 中访问此列表,如下所示:
<body>
<c:forEach var="student" items="${students}">
Id: ${student.id}
Name: ${student.name}
</c:forEach>
</body>
你的Student.java
public class Student{
private String id;
private String name;
private String getId(){
return id;
}
private void setId(String id){
this.id = id;
}
private String getName(){
return name;
}
private void setName(String name){
this.name = name;
}
}
关于java - 如何使用 JSP、Servlet、Hibernate 显示来自 SQL Server 的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25893892/