1

I am trying to retrieve an array list object of type QueryClass from a servlet I have made and import the class of the QueryClass so I can use the object in my jsp called validate.jsp" but the object seems not to exist when I get the attribute in the jsp file, though in my servlet its initialized with the appropriate data and I set it with the right name.

In my servlet I have this snippet

QueryClass query = new QueryClass("","","","");

String searchName = request.getParameter("searchName");

ArrayList<QueryClass> data = query.getSearchedNames(searchName);

request.setAttribute("data",data);  

RequestDispatcher rd = request.getRequestDispatcher("validate.jsp");

rd.forward(request, response);

In my jsp I have the following

<%@page import="src.main.java.QueryClass"%>

<%
if(request.getAttribute("data")!=null) 
{
    ArrayList<QueryClass> value = (ArrayList<QueryClass>)request.getAttribute("data");
}
%>
Advaita Gosvami
  • 358
  • 1
  • 11
Raymond Nakampe
  • 371
  • 7
  • 22
  • Sorry about the little code errors about typecasting and not including the brace. They are in there in my code. – Raymond Nakampe Apr 25 '13 at 11:14
  • 2
    Ideas: (1) put a breakpoint to ensure that data is actually what you expect it to be (as it's far from obvious with the given code) and (2) get rid of scriptlets and refer to data as `${data}` in your JSP. – skuntsel Apr 25 '13 at 11:24
  • Hi Skuntsel, thanks for your reply, do I need to assign "${data}" to something because I want to traverse the data and show it in a data afterwards. – Raymond Nakampe Apr 25 '13 at 12:07
  • Read here: [How to avoid Java code (scriptlets) in JSP files?](http://stackoverflow.com/a/3180202/814702) – informatik01 Apr 25 '13 at 19:40

1 Answers1

1

Your requirements are basically fulfilled by keeping in mind a MVC approach that basically made scriptlets obsolete and deprecated.

  1. Set the data you want as a request attribute in a servlet method:

    List<QueryClass> data = createList(...);
    request.setAttribute("data",data);
    request.getRequestDispatcher("validate.jsp").forward(request, response);
    
  2. Access different properties of request (session, application, etc.) via EL:

    ${data}
    

So, to keep in mind your desire to traverse the list, the traversal could have the following style in JSP if you used JSTL:

<ul>
    <c:forEach var="element" items="${data}">
        <li>${element.name}</li>
    </c:forEach>
</ul>

The code above will generate a list of names of each element from your data object, provided that your class has getName() method defined.

skuntsel
  • 11,624
  • 11
  • 44
  • 67
  • Thanks Skuntsel, I shall have a look at the JSTL as I am not familiar with, if I may ask, do you think the importing of my class is wrong because I have both my queryclass and my servlet class in the same folder which is "src/main/java/". So does my import have a mistake or something ? – Raymond Nakampe Apr 25 '13 at 14:33