-1

I'm trying to display data in JSP by a servlet but I get a null object after getting the parameter:

This is my doGet function in the servlet:

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);
}

And this is how I read the result:

<%
    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); 
    ...
%>

Thanks in advance!!

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
nash
  • 523
  • 1
  • 5
  • 18
  • Have you import the class in th jsp? – yaylitzis Dec 03 '15 at 19:36
  • 1
    You could be getting a null pointer due to a number of reasons (StudentManager, EntityManagerFactory, etc.). I think the underlying problem is that you are attempting to 'jam' all of your code into a scriptlet in the jsp. It may behoove you instead to conform to the JSP Web App convention and place all server side logic into a tag handler instead. – andrewdleach Dec 03 '15 at 19:39

1 Answers1

0

If you want to use an object in the jsp, you have to import it first. Be sure that your class is public and then import it like:

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

You can also try to save the list to the session variable (if you have) with session.setAttribute("stList", result); and then in JSP

 List<Student> stList = (List<Student>) session.getAttribute("stList");
yaylitzis
  • 5,354
  • 17
  • 62
  • 107
  • I've already imported my Student class. I've tried to save the list to the session var as you said, but I get a java.lang.NullPointerException error... – nash Dec 03 '15 at 19:54