views:

103

answers:

2

I'm getting a NullPointerException that I couldnt handle. I'm a newbie in java so I'd appreciate any help.

<%
Employee employees[] = (Employee []) request.getAttribute("arr");
Integer arr_size= (Integer) request.getAttribute("arr_size");
for(int i=0;i<employees.length;i++){ %>
<tr><td><b>.</b></td><td><%=employees[i].getName()%></td><td>
    <%=employees[i].getLname()%></td><td><%=employees[i].getType()%></td><td>
    <%=employees[i].getEmail()%></td><td><a href="">Edit Employee Details</a></td>
</tr>
<%}%>

arr array and arr_size is passed from a servlet and I jsp gives an NullPointerException.

I tried checking if employees and arr_size is null or not but it doesn't change anything.

thanks.

+3  A: 

Even if the array itself isn't null, it's quite possible that employees[i] would be null - leading to a NullPointerException. You could avoid this by skipping such elements:

for(int i=0;i<employees.length;i++) { 
    if (employees[i] == null) {
        continue;
    }
%>

It's not terribly elegant, mind you. I'd also suggest using the enhanced for loop if you're compiling with Java 5, which would make the code cleaner:

<%
Employee employees[] = (Employee []) request.getAttribute("arr");
for (Employee employee : employees) {
    if (employee == null) {
        continue;
    } %>
<tr><td><b>.</b></td><td><%=employee.getName()%></td><td>
    <%=employee.getLname()%></td><td><%=employee.getType()%></td><td>
    <%=employee.getEmail()%></td><td><a href="">Edit Employee Details</a></td>
</tr>
<%}%>

Note that I've ignored arr_size as you didn't appear to be using it. What was it meant to represent?

Finally, I'd suggest moving logic outside your JSP if at all possible...

Jon Skeet
What logic? All he's doing is printing out the contents. It's not like he's doing calculations on them or something.
Paul Tomblin
thanks a lot skeet.
huhuhuuu
I agree about leaving logic out of the jsp but I need to display an array as you see, is there a way to to that other than this way?
huhuhuuu
Kudos on your analysis skills, Jon Skeet! But I'd like to inject that it's not a good idea for darcrc to become dependent on SO like this. "Teach a man to fish" and all that. So he needs to learn where to find the stack trace (which makes finding the bug much, much easier).
Carl Smotricz
@Paul: I agree that it's not doing a lot of logic, but it's still ugly including all of that plain Java code within the JSP. I prefer to use technologies which don't mix things up quite so much.
Jon Skeet
A: 

They only thing that I can see that you haven't checked yet is the elements of your employees array. If employees[i] is null at any point, referencing it will throw a NullPointerException.

Try this:

for(int i=0;i<employees.length;i++){ 
  Employee e = employees[i];
  if (e != null) {%>
    //current code you have goes here
  <% }} %>

instead of the current for loop

Jorn
the Skeet beat me to it ;(
Jorn
thanks a lot anyway :D problem is solved
huhuhuuu