Main Tutorials

jQuery and Java List example

There is no direct way to iterate over a Java List with jQuery, see the following case study :

Spring controller

	@RequestMapping(value = "/", method = RequestMethod.GET)
	public ModelAndView getPages() {
	
		List<String> list = new ArrayList<String>();
		list.add("List A");
		list.add("List B");
		list.add("List C");
		list.add("List D");
		list.add("List E");
		
		ModelAndView model = new ModelAndView("somepage");
		model.addObject("list", list);
		
		return model;

	}

JSP page, you can access the list object via ${List}, and iterate over it via JSTL.

somepage.jsp

    <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

    <c:forEach var="listValue" items="${list}">
	<li>${listValue}</li>
    </c:forEach>

What if I want to pass the List object to jQuery directly?

Problem : There are no double quotes in Java List

Example to iterate over a Java List with jQuery $.each().

html page

<script>
	$(document).ready(function() {

		var list = ${list};
		$.each(list, function( index, value ) {
			alert( index + ": " + value );
		});
		
	});
</script>

Above jQuert script will not be executed “Uncaught SyntaxError: Unexpected token , ”

html page (source code)

<script>
        $(document).ready(function() {

	    var list = [List A, List B, List C, List D, List E];
	    $.each(list, function( index, value ) {
		alert( index + ": " + value );
	    });

        });
</script>

Review above html source code, Java List didn’t enclose the List’s values with double quotes ", so, jQuery unable to process it.

Solution : Convert Java List to JSON

The solution is converts the Java List into JSON format before pass it to jQuery. In Spring controller, use Jackson (or other JSON processors)to convert the List into JSON format.


	@RequestMapping(value = "/", method = RequestMethod.GET)
	public ModelAndView getPages() {
	
		ObjectMapper mapper = new ObjectMapper();
		
		List<String> list = new ArrayList<String>();
		list.add("List A");
		list.add("List B");
		list.add("List C");
		list.add("List D");
		list.add("List E");
		
		ModelAndView model = new ModelAndView("somepage");
		
		String json = "";
		try {
			json = mapper.writeValueAsString(list);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		model.addObject("list", json);
		
		return model;

	}
html page

<script>
	$(document).ready(function() {

		var list = ${list};
		$.each(list, function( index, value ) {
			alert( index + ": " + value );
		});
		
	});
</script>

Review html source code :

html page (source code)

<script>
        $(document).ready(function() {

	    var list = ["List A","List B","List C","List D","List E"];
	    $.each(list, function( index, value ) {
		alert( index + ": " + value );
	    });

        });
</script>

Done.

Note
To loop over a object array in JSON formatted string, you need to converts it to JavaScript object (with JSON.parse() or $.parseJSON()) before parse it with jQuery $.each(). See this example – JQuery Loop Over JSON String

References

  1. JQuery Loop Over JSON String – $.Each Example
  2. jQuery $each() example
  3. Spring MVC and List example
  4. Wikipedia : JSON
  5. Jackson – High-performance JSON processor.

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
7 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Naresh
4 years ago

what if i want iterate over a java model object in jquey and print the values.please explain
In Jsp i have

//list comes from servlet
and this id values i want to iterate in for loop and print in js

Brahmaiah
3 years ago

How to compare index and values with my own values..in Jquery and when condition true, i have to update only particular index value and the values kept to the previous list and shows it in jsp with out reload the page

dev17
9 years ago

Hi I am using JSF , Can you tell me how this can be done in JSF framework . I see here you see ModelandView . In that is there something that I can use in JSF and maven based project

Johaness
9 years ago

why dont you refer what kind of framework are you using? java is not so easy on this way, you must refer all the dependencies, without that its useless sample.

kyu
10 years ago

Thanks for your post

g00glen00b
10 years ago

Your HTML output is always missing the document ready part:

$(document).ready(function() {
// …
});

I was thinking that it might be confusing.