0

Basically I have this function that allows people to search for other user based on their usernames. You type into the textbox id="search" and it will look for users with that username/similar username:

<form name="searchForm" action="searchUser"  method="post">
<input type="text" id="search" name="search" placeholder="Search.." />
<input type="submit" id="searchButton" name="searchButton" value="Search!" onclick="searchUsers()"/>
</form>

This is the servlet SearchUserServlet that maps to the action searchUser.The static method searchUser(string) returns an arraylist of user objects. I am trying to pass this arraylist to QuickMatchResult.jsp:

public class SearchUserServlet extends HttpServlet {
 private static final long serialVersionUID = 1L;
    public void doPost(HttpServletRequest request, HttpServletResponse response){

        try {

            String name=request.getParameter("search");
       ArrayList<User> userList=  User.searchUser(name);



            RequestDispatcher dispatcher=request.getRequestDispatcher("/QuickMatchResult.jsp");
            request.getSession().setAttribute("userList",userList);
            dispatcher.forward(request, response);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }catch(Exception e){
            e.printStackTrace();
        }
    }

This is the QuickMatchResult.jsp where it is forwarded. I'm trying to show all the usernames of the user objects in the arraylist:

<table id="searchResults">
<%      ArrayList<User> userList= new ArrayList<User>();
userList=(ArrayList<User>)request.getAttribute("userList");
for (int i=0; i<userList.size();i++){
User user=userList.get(i);
%>
<tr>
<td><%=user.getUserName()%></td>    
</tr>
<%

}
%>
</table>

However when I try to run this, I get a null pointer exception. Any idea why?

Blaiz
  • 105
  • 1
  • 6
  • 12

2 Answers2

0

You have set your attribute in the session and not in request. Use

request.setAttribute("userList", userList);

or if you want to use session, then retrieve the session attribute in JSP.

session.getAttribute("userList");

We get NullPointerException when we are trying to call a method on the object reference which does not refer to object. i.e. null.

In your case, you are trying to retrieve an attribute named userList from the request object, but there is no any attribute as such in request. If getAttribute does not find the attribute, it returns null

Prasad Kharkar
  • 13,410
  • 5
  • 37
  • 56
0

You are putting the userList in sesion object and trying to retrieve it from request object. Get this list from session not from the request.Below should help

userList=(ArrayList<User>)session.getAttribute("userList");
ajay.patel
  • 1,957
  • 12
  • 15