null pointer exception help
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&g开发者_开发知识库t;<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.
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...
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
精彩评论