Search code examples
javascriptjavaajaxspringstruts

Pass array list back to struts jsp using spring controller?


Working with two projects, one built on struts and one built on spring. I need to be able to make an ajax call to bring back a list of objects so that I can display them in the html for the struts project. Currently the ajax call to the controller is working correctly but I'm having trouble passing back the array list. Any suggestions?

javascript

$.ajax({
    url: 'sampleUrl.com/controller/call',
    success: function(data) {
        //handle returned object
    }
}

Controller method

@RequestMapping(value = 'call', method = RequestMethod.Get)
public @ResponseBody List<SampleObject> getSampleObjects(HttpServletRequest request) {
     List<SampleObject> sampleList = new ArrayList<SampleObject>();
     sampleList.add(new SampleObject());
     return sampleList;
}

Solution

  • In the controller I had to add produces="application/json" to the @RequestMapping and before the return create a new Gson and return gson.ToJson() of the list. On my jsp file I it was able to loop through the list normally once the JSON was returned by adding dataType: 'json' to the ajax call.

    javascript

    $.ajax({
        url: 'sampleUrl.com/controller/call',
        dataType: 'json',
        success: function(data) {
            for(var i = 0; i < data.length; i++) {
                console.log(data[i]);
            }
        }
    }
    

    Controller:

    @RequestMapping(value = 'call', method = RequestMethod.Get, produces="application/json")
    public @ResponseBody String getSampleObjects(HttpServletRequest request) 
    {
         List<SampleObject> sampleList = new ArrayList<SampleObject>();
         sampleList.add(new SampleObject());
         Gson gson =  new Gson();
         return gson.toJson(sampleList);
    }