views:

197

answers:

4

Is it possible to have a servlet that contains an object (an ArrayList in this case) that then does the equivalent of displaying a jsp page and passing that object to the jsp page. In this case the ArrayList contains database results an I want to iterate through and display the results on the JSP page.

I am not using any MVC framework, is it possible to do this with the basic Servlet/JSP architecture.

+1  A: 

You can pass objects to jsp's by embedding them within the Request.

request.setAttribute("object", object);

and within the jsp:

request.getAttribute("object");

kgrad
What should I google to get more info, I don't seem to get anything.
Ankur
+1  A: 

You can put it using request.setAttribute("myobj", myObj); see javadoc

splix
+4  A: 

Yes.

  1. in the servlet call request.setAttribute("result", yourArrayList);
  2. then forward to the jsp:

    getServletContext().getRequestDispatcher("your.jsp")
        .forward(request, response);
    
  3. using JSTL, in the jsp:

    <c:forEach items="${result}" var="item">
      ...
    </c:forEach>
    

If you don't want to use JSTL (but I recommend using it), then you can get the value using request.getAttribute("result") in the JSP as well.

Alternatively, but not recommended, you can use request.getSession().setAttribute(..) instead, if you want to redirect() rather than forward().

Bozho
Note that the reason for the redirect() approach not being recommended, is because you tell the browser to go to a new URL causing a new request where the "request" scope is different, hence the result cannot be stored in "request"-scope (request.setAttribute...) but must be stored in a scope available to a new request. In standard JSP there is only the session scope available where objects live forever which is usually not desired. I believe MyFaces Orchestra has an interesting alternative - http://myfaces.apache.org/orchestra/myfaces-orchestra-core/installation.html
Thorbjørn Ravn Andersen
yes, but that's too much, since he doesn't want to use an mvc framework
Bozho
+1  A: 

If you are trying to make some kind of "component" then it's better to convert the JSP page into a custom tag. Here is excellent article about that: http://onjava.com/pub/a/onjava/2004/05/12/jsp2part4.html

Alex Tracer
Thanks, I actually do that now. It's much neater.
Ankur