Rajeshwar
Rajeshwar

Reputation: 11681

Scriptlet in JSP - Accessing request objects

I know its best to use jstl in JSPS but I have been explicitly told to use scriptlets in this project.My question is that my servlet attached an item of Arraylist to the request object and i wanted to loop over that item using scriptlet.

Example : My servlet attaches this and forwards it to a jsp

 request.setAttribute("list", Content); where Content is Arraylist<String>

The jsp is to retrieve this object and print it on the page which i tried is:

  <%    
          ArrayList<String> cont =  (ArrayList)request.getAttribute("Content");
          for (int i=0;i<cont.size();i++)
          {
              out.println(cont.get(i));

          }
   %> 

Here is the error that i get

org.apache.jasper.JasperException: An exception occurred processing JSP page /EnrolledSuccess.jsp at line 35

32:           ArrayList<String> cont =  (ArrayList)request.getAttribute("cont");
33:           for (int i=0;i<=cont.size();i++)
34:           {
35:               out.println(cont.get(i));
36:               
37:           }
38:    %> 

Upvotes: 6

Views: 28400

Answers (4)

Joe
Joe

Reputation: 1

first, you must get attribute from request.
<br/>
<%<br/>
  ArrayList<String> list = (ArrayList<String>)request.getAttribute("list");<br/>
    for(int i = 0; i < list.size(); i++){<br/>
        //you can print the value<br/>
        out.printLn(list.get(i));<br/>
    }<br/>
%><br/>

Upvotes: 0

phalgun dandu
phalgun dandu

Reputation: 11

Index for ArrayList starts from "0", so in for loop the condition should be either i

Upvotes: 0

Ramesh Kotha
Ramesh Kotha

Reputation: 8322

Try iterating Arraylist elements with Iterator.

out.println prints to the browser and System.out.println() prints to the server console.

<%    
          ArrayList<String> cont =  (ArrayList)request.getAttribute("list");
          Iterator<String> itr = cont.iterator();
          while (itr.hasNext()) {
          String element = itr.next();
          out.println(element);
    }
   %> 

Upvotes: 6

FSP
FSP

Reputation: 4827

have you tried request.getAttribute?

Upvotes: 0

Related Questions