faraa faraa - 11 months ago 68
JSON Question

return json object list from spring mvc controller

I want to return json object list from spring controller and use it in view but it returns empty list!
I can not understand the problem.
I create activities objects in minutesController and return it as json.But I can't get it in form using jquery.
But I can see correct result in browser when I try localhost:8080/FitnessTracker5/activities.json.
My server is glassfish


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<title>Add Minutes Page</title>
<script type="text/javascript" src="/WEB-INF/pages/jquery-3.1.0.js"></script>
<script type="text/javascript">
$.getJSON('localhost:8080/FitnessTracker5/activities.json' , {

var html = '<option value="">please select one--</option>'
var len = data.length;

for(var i=0 ; i<len ;i++){
html += '<option value="' + data[i].desc + '">'
+data[i].desc+ '</option>' ;
html +='</option>';


<h1>Add Minutes Excersisedddd:</h1>

Language:<a href="?language=en">English</a> | <a href="?language=fa">Persian</a>
<form:form commandName="exercise">


<td><h1><spring:message code="goal.text"/> </h1> </td>
<td> <form:input path="minutes"/></td>
<form:select id="activities" path="activity"></form:select>





public class Activity {
private String desc ;
public String getDesc() {
return desc;

public void setDesc(String desc) {
this.desc = desc;



public class MinutesController {

@RequestMapping(value = "/addMinutes")
public String addMinutes(@ModelAttribute("exercise") Exercise exercise){
System.out.println("exercise" + exercise.getMinutes());
System.out.println("exerciseeeee" + exercise.getActivity());
return "addMinutes" ;

@RequestMapping(value = "/activities" , method = RequestMethod.GET)
public @ResponseBody List<Activity> findAllActivities(){
List<Activity> activities = new ArrayList<Activity>();

Activity run = new Activity();
activities.add(run) ;

Activity bike = new Activity();
bike .setDesc("Bike");
activities.add(bike) ;

Activity swim = new Activity();
activities.add(swim) ;

return activities;


@RequestMapping(method=RequestMethod.GET, value ="/test")
public @ResponseBody Activity getMovie( ){

Activity activity = new Activity();
return activity;

Answer Source

From your comment above it appears the problem is that JQuery cannot be loaded, which is probably due to a misconfigured dispatcher servlet. You might try accessing jquery from the CDN instead:

<script type="text/javascript" src="//code.jquery.com/jquery-3.1.0.min.js"></script>

If you want to serve jquery from your application you should google for "serve static resources Spring MVC" :)

And add http:// to url.

 $.getJSON('http://localhost:8080/FitnessTracker5/activities.json' , {