2

I'm passing an arraylist from servlet by setting it in the attribute and forwarding it to the jsp

Servlet:

ArrayList <String> mylist = new ArrayList <String>();

mylist.add("Superman");

mylist.add("batman");

mylist.add("flash");

request.setAttribute("mylist", mylist);

request.getRequestDispatcher("Welcome.jsp").forward(request, response);
response.sendRedirect("Index.jsp");

Index.jsp

function doPopulateList(obj)
    {

     alert("HELLO"+obj.id +obj.name+obj.value);
     var select = document.getElementsByClassName("my_dropdown1"); 
     alert("all good");
     //var list = new Array();
      var list = '${mylist}'; 
      //var options = ["1", "2", "3", "4", "5"]; 

     alert("All good till arraylist");
     for(var i=0;i<list.length;i++)
         {

         alert(list[i]);

         }

When I'm trying put the arraylist values in the alert box, I'm getting alerts like

[
S
U

I want the alerts to be like

Superman
batman
flash

Pardon me if this is duplicate question.

1
  • Ooops wrong place. Commented Jun 21, 2017 at 14:01

2 Answers 2

2

Firstly, you need to traverse the server-side list and add each element to JS array before the servlet does not send the response to the client.

So, this might work:

<script>
   var list = [
      <c:forEach items="${mylist}" var="hero">
        '<c:out value="${hero}" />',  
      </c:forEach>
   ];
   console.log(list);
</script>
Sign up to request clarification or add additional context in comments.

Comments

0

What's arriving on the client side is not an array but a string. Therefore if you loop you are looping the single characters of the String.

You need to convert the string to a JSON-Object in order to be able to loop the list items.

var list = JSON.parse('${mylist}');

2 Comments

How do I traverse through the JSON object? I'm sorry for asking this but I've no idea about JSON.
Sorry, it took so long. I was away from the computer. What you actually get is an array. I misnamed it object. Just do your regular for-loop in javascript.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.