Bhargav
Bhargav

Reputation: 918

NullPointerException when iterating over ArrayList in jsp

I am displaying a list which contains objects which store message information. The list is loaded through getting the request as such:

ArrayList<MessageModel> list = (ArrayList<MessageModel>) request.getAttribute("msgList");

I am trying to display information contained in each object as such:

for(MessageModel msg : list){
                String messageTo = msg.toAddress;
                String messageSub = msg.messageSubject;
                out.println(messageTo+ " " +messageSub);
            }

I am getting a NullPointerException at the for each statement.

As an aside, I am using this approach to debug as I want to check whether or not I can display the content of the MessageModel object at all. I tried using JSTL forEach tag but I could not access the object attributes.

 <c:forEach items="${list}" var="current">
     <li><c:out value="${current.toAddress}"/></li>
 </c:forEach>

I set the attribute like this :

 ArrayList<MessageModel> list =(ArrayList<MessageModel>) request.getAttribute("msgList");
 pageContext.setAttribute("messages", list);

This results in the following error message when run :

org.apache.jasper.JasperException: /inbox.jsp (line: 37, column: 12) According to TLD or attribute directive in tag file, attribute items does not accept any expressions

And intelliJ says that it cannot resolve the variable list.

EDIT :

I forward the request from a servlet that handles user login as follows :

 ArrayList<MessageModel> msglist = MessageModel.getRecievedMessages(username);
 request.setAttribute("msgList", msglist);

I am trying to pass the ArrayList that contains the message objects and then iterate over the list and display it in the jsp.

Is there a possibility for the jsp itself to get the information ? I have a separate java class which handles the messages with a bunch of helper functions. So can I call the method that retrieves all those messages and display them without explicitly setting a request attribute in the servlet ? Because I will be navigating between other pages in the application.

Sorry if my vocabulary was off, this is the first time I am working with jsp's and servlets.

Upvotes: 1

Views: 4853

Answers (2)

Bhargav
Bhargav

Reputation: 918

I solved this problem by using creating getter and setter methods to get the class members of MessageModel.

EL tag wiki: this article helped me understand how to interface a java class and a jsp.

Upvotes: 0

Benjamin
Benjamin

Reputation: 1846

The NullPointerException in the foreach loop is probably due to the list variable being null. You may check for listnot being null before iterating over it.

Regarding the JasperException, can you describe how you forward to the JSP ?

Also, it's probably a typo, but you set an attribute named messages, then you iterate over an attribute named list in the <c:foreach>...

Upvotes: 2

Related Questions