从数据库中读取数据并在JSP中显示

时间:2015-12-03 19:34:28

标签: java jsp servlets

我试图通过servlet在JSP中显示数据,但在获取参数后得到一个null对象:

这是我在servlet中的doGet函数:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    PrintWriter out = response.getWriter(); 

    EntityManagerFactory emf = Persistence.createEntityManagerFactory("AdministracionWeb");

    StudentManager sm = new StudentManager();
    sm.setEntityManagerFactory(emf);

    List<Student> result = sm.getAllStudents();
    // result contains a correct value
    //out.println(result);
    request.setAttribute("stList", result);
          request.getRequestDispatcher("students.jsp").forward(request,response);
}

这就是我读取结果的方式:

<%
    List<Student> stList = (List<Student>) request.getAttribute("stList");
    // stList here is null (why???)
    Student st = new Student();
    for (int i = 0; i < stList.size(); i++){
        st = stList.get(i); 
    ...
%>

提前致谢!!

1 个答案:

答案 0 :(得分:0)

如果要在jsp中使用对象,则必须先导入它。确保您的课程是公开的,然后将其导入:

<%@ page import="yourPackage.Student%>

您也可以尝试使用session.setAttribute("stList", result);将列表保存到会话变量(如果有),然后在JSP中

 List<Student> stList = (List<Student>) session.getAttribute("stList");