Raymond Nakampe
Raymond Nakampe

Reputation: 371

Importing and retrieving a class object in a jsp

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");
}
%>

Upvotes: 1

Views: 1268

Answers (1)

skuntsel
skuntsel

Reputation: 11742

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.

Upvotes: 1

Related Questions