3

I have a Java (Spring MVC) backend that returns POJOs as JSON objects as follows:

@RequestMapping(value = "/getWidgetsByType", method = RequestMethod.POST)
public @ResponseBody List<WidgetVO> getWidgetsByType(@RequestParam("type") String type)
{
    return widgetDAO.getWidgetsByType(token);
}   

public class WidgetVO {
    private String type;
    private String name;
    private boolean isAwesome;

    // Getters and setters, etc.
}

In the frontend I'm trying to call /getWidgetsByType from inside a jQuery $.getJSON call, and then use the JSON results coming back from that to populate a datatable. Specifically, I want the datatable to appear inside a <div> tag that is currently empty at page load as follows:

<div id="#table-to-display"></div>

var t = getTypeFromDOM();

$.getJSON(
    url: "/getWidgetsByType",
    data: {
        type: t
    },
    success: function() {
        // How do I extract the JSON version of the List<WidgetVO>'s coming
        // back from the server and use them to populate the table?
        $("#table-to-display").datatable();
    }
);

I would like the datatable to contain the same columns as the fields of the WidgetVO (type, name, isAwesome), all as String values (no renderers, etc.).

Thanks in advance for any help here!

3 Answers 3

2

1.Controller

@RequestMapping(value = "/json", method = RequestMethod.GET)
public
@ResponseBody
String listUsersJson(ModelMap model) throws JSONException {
    int no=1;
    JSONArray userArray = new JSONArray();
    for (TileType tT: tD.getAll()){   
        String n=Integer.toString(no);
        String id=Integer.toString(tT.getTileTypeId());          
        String[] value =
        {n,
         tT.getTileTypeName(),
         tT.getTileTypeDensity()         
        };   
        userArray.put(value);
        no++;
    }
    String x=userArray.toString();
    String replace1=x.replace("{", "[");
    String replace2=replace1.replace("}","]");
    String replace3=replace2.replace(":",",");
   return ("{\"aaData\":"+replace3+"}");        
}

2.Dao

 @Override
public List<TileType> getAll() {
    Session session=HibernateUtil.getSessionFactory().openSession();
    List<TileType>list=new ArrayList<TileType>();
    try{
    Query query=session.createQuery("from TileType T order by T.tileTypeId DESC");
    list=query.list();
    }
    catch(HibernateException he){}
return list;
   }

3.Javascript

var table = $('#example').dataTable({
     "sPaginationType": "full_numbers",
    "sAjaxSource": "/data/tipeTile/json",
    "sDom": "<'row'<'col-xs-6'l><'col-xs-6'f>r>t<'row'<'col-xs-6'i><'col-xs-6'p>>",
    "sPaginationType": "bootstrap",
    "oLanguage": {
        "sLengthMenu": "_MENU_ records per page",
        "sSearch": ""
    }
         }); 

4.Html

  <table cellpadding="0" cellspacing="0" border="0" class="table table-striped table-bordered" id="example">
                            <thead>
                                <tr>
                                    <th style="width: 50px">No</th>
                                    <th>Name</th>
                                    <th>Density</th>

                                </tr>
                            </thead>
                            <tbody>

                            </tbody>
                        </table>

Hope this Help

Sign up to request clarification or add additional context in comments.

Comments

1

Example from the datatable site gives you all the details required.

Example JS code

$(document).ready(function() {
  $('#example').dataTable( {
    "bProcessing": true,
    "bServerSide": true,
    "sAjaxSource": "scripts/server_processing.php" // for you it will be - /getWidgetsByType
  } );
} );

Your json should be something like this

{
  "sEcho": 1,
  "iTotalRecords": "57",
  "iTotalDisplayRecords": "57",
  "aaData": [
    [],[],[],...
  ]
}

Here's example showing to set the column names on the fly.

Cheers!!

7 Comments

Thanks @bhb (+1) - but are bProcessing and bServerSide datatable params or app-specific query string params? What if my server-side is not a PHP file but a Spring MVC handler that gets mapped from the URL /getWidgetsByType? Thanks again!
It should not matter as long as your server side code pushes json format shown above. If that is difficult for some reason, you can also read from other sources. Check this. If your json is an array of objects(instead of array of array as shown above) try something like this
So do I even need to call $.getJSON, or does the $("#table-to-display").datatable() { ... }; call do it for me?
No probs :). So if the json is an array of array like {demo:[[],[]...]}, then the order of the array elements specifies the column order.
That's so cool. Thanks again - all the lightbulbs (well, most of them) just went on. thanks for helping me connect the dots
|
1

The easiest way to get the appropriate JSON data from Spring to DataTable is that instead of returning a list of your entity, return a map like this:

    @RequestMapping(value = "/getWidgetsByType", method = RequestMethod.POST)
public @ResponseBody Map<String, WidgetVO> getWidgetsByType(@RequestParam("type") String type) {
    Map<String, WidgetVO> result = new HashMap<>();
    result.put("WidgetVO", widgetDAO.getWidgetsByType(token));
    return result;
}

That's it and now you can have access to your objects:

 $(document).ready(function() {
$('#example').dataTable( {
    "ajax": "data/objects.txt",
    "dataSrc": "WidgetVO",
    "columns": [
        { "data": "type" },
        { "data": "name" },
        { "data": "isAwesome" }

    ]
});

});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.