0

I have a arraylist returned from my controller to jsp, now I want to use that arraylist to populate the datatable. This is what I have done, but it is not working:

$(document).ready(function() {
  //grpAlphaInfoVO is the arraylist returned by my controller
  $('#groupAlphaList').dataTable({
    "aaData": "${grpAlphaInfoVO}"
  });
});

This is my controller code:

@RequestMapping(value = "/groupAlpha/search/{groupName}", method = { RequestMethod.GET, RequestMethod.POST })
public ModelAndView groupAlphaHandler(@PathVariable("groupName") String groupName, HttpServletRequest request) {

    ArrayList<GroupAlphaInfoVO> grpAlphaInfoVO = groupAlphaService.loadGroupAlphaSearchResult(groupName);
    if(grpAlphaInfoVO != null) {
        ModelAndView mav = new ModelAndView("group-alpha");
        mav.addObject("grpAlphaInfoVO", grpAlphaInfoVO);
        mav.addObject("pageTitle", "Group Alpha");
        return mav;
    }
}
abhi
  • 1,920
  • 6
  • 24
  • 27
  • what do you mean by not working? what error you are getting – Aman Chhabra Jul 12 '18 at 15:59
  • Please don't just say "It's not working" explain how it isn't working – Get Off My Lawn Jul 12 '18 at 15:59
  • the data is not populating.... getting blank datatable – abhi Jul 12 '18 at 16:00
  • what is ${grpAlphaInfoVO}.... is it a Javascript varialbe or a Java varialbe and what is the output when you debug – Aman Chhabra Jul 12 '18 at 16:01
  • 1
    @AmanChhabra it probably should be replaced with tick marks or just be a variable instead of a string... Probably why the code isn't working – Get Off My Lawn Jul 12 '18 at 16:03
  • @GetOffMyLawn I agree – Aman Chhabra Jul 12 '18 at 16:04
  • grpAlphaInfoVO is a java variable.... its an arraylist – abhi Jul 12 '18 at 16:06
  • 1
    Java or JavaScript? – Get Off My Lawn Jul 12 '18 at 16:06
  • @GetOffMyLawn java varaible, returned by controller – abhi Jul 12 '18 at 16:13
  • Okay then, we will also need to see your java code that generates that variable. – Get Off My Lawn Jul 12 '18 at 16:13
  • @abhi how can you put arraylist like this in datatable... one option is to convert it into JSON string and then use – Aman Chhabra Jul 12 '18 at 16:14
  • Paste more code. How is the controller called? – Pavel Molchanov Jul 12 '18 at 16:14
  • edited post with controller code – abhi Jul 12 '18 at 16:17
  • Okay, it looks like you are trying to use a java variable within javascript. This cannot be done. The two are not interchangeable. You need to make a JSON string from that variable and pass the string to JavaScript which then can use `JSON.parse(myJSONString)` to convert that data into a readable JavaScript object. – Get Off My Lawn Jul 12 '18 at 16:24
  • @GetOffMyLawn you mean i should convert the grpAlphaInfoVO into json string in my controller and return that, if yes then how to convert grpAlphaInfoVO into JSON string? – abhi Jul 12 '18 at 16:28
  • You can do it like this: https://stackoverflow.com/questions/24616174/how-to-convert-arraylist-to-json-object – Get Off My Lawn Jul 12 '18 at 16:30
  • 1
    @GetOffMyLawn `` Is this the correct way to do it? Note: grpAlphaINnfoVO is the josn string now – abhi Jul 12 '18 at 17:09
  • Agree.. Tried to share a small working example here: https://stackoverflow.com/a/51311135/1262248 – Aman Chhabra Jul 12 '18 at 17:11
  • No, JavaScript does **NOT** have access to you Java variables. I do not have enough Java experience on how to get that variable from a to b, but it needs to be done. – Get Off My Lawn Jul 12 '18 at 17:11
  • @GetOffMyLawn Yes, we __CAN__ . OP has implemented JSP and can use JSON String on JSP page using _<%= grpAlphaInfoVOJSONString %>_ – Aman Chhabra Jul 12 '18 at 17:14
  • Can you add JavaScript code where you are calling server-side controller, please? It's still not clear how your calling controller from the JavaScript. – Pavel Molchanov Jul 12 '18 at 18:22
  • @PavelMolchanov I am calling the controller from jsp, using RequestMapping in spring – abhi Jul 12 '18 at 18:24
  • Can you share the code how you are calling controller in JSP? @RequestMapping doesn't call the controller. It defines the endpoint that can be called, but it's not calling anything. – Pavel Molchanov Jul 12 '18 at 18:33
  • `@RequestMapping(method = { RequestMethod.POST, RequestMethod.GET }, params = "searchType=benefit") public String benefitSearch(@ModelAttribute("searchForm") SearchForm form, BindingResult result, Model model) { if (form.getSearchValue() == null || (form.getSearchValue().length() != 9 && form.getSearchValue().length() != 6)) { result.rejectValue("searchValue", "benefit.length"); return "search"; } return "redirect:/benefit/search/" + form.getSearchValue(); }` This is my searchController.java, so when i check a radio button it selects the appropriate method – abhi Jul 12 '18 at 18:35
  • @AmanChhabra can you look at this problem, https://stackoverflow.com/questions/51544999/column-wise-search-giving-227200101-uncaught-typeerror-otable-api-columns-i – abhi Jul 27 '18 at 18:33
  • @PavelMolchanov can you look at this problem, https://stackoverflow.com/questions/51544999/column-wise-search-giving-227200101-uncaught-typeerror-otable-api-columns-i – abhi Jul 27 '18 at 18:33

3 Answers3

0

First of all you need to convert JAVA ArrayList to JSON.

For this you can use GSON library.

JAVA code to convert list to JSON:

public class Test {

    static class Entry{
        String data1;
        Entry(String data1){
            this.data1 = data1;
        }
    }
    public static void main(String[] args) {
        List<Entry> data = new ArrayList<>();
        data.add(new Entry("somevalue"));
        data.add(new Entry("otherRandomValues"));
         String json = new Gson().toJson(data);
         System.out.println(json);
    }

}

Output:

[{"data1":"somevalue"},{"data1":"otherRandomValues"}]

Then need to transfer data from Servlet to JSP using <%= grpAlphaInfoVOJSONString %> where grpAlphaInfoVOJSONString is the name of variable having JSON string in controller

Please refer below link for better understanding:

Transferring data from servlet to jsp page

And then you need to use JSON to implement data table as in below example:

$(document).ready(function() {
var grpAlphaInfoVOJSON = [{"column1":"somevalue"},{"column1":"otherValues"}];
  //grpAlphaInfoVO is the arraylist returned by my controller
  $('#groupAlphaList').dataTable({
    "data": grpAlphaInfoVOJSON,
    "columns" : [
            { "data" : "column1" }
            ]
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/v/dt/dt-1.10.18/datatables.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/dt-1.10.18/datatables.min.css"/>
<table id="groupAlphaList" class="display" width="100%"></table>
Aman Chhabra
  • 3,824
  • 1
  • 23
  • 39
  • `var grpAlphaInfoVOJSON = [{"column1":"somevalue"},{"column1":"otherValues"}];` here how can I use my java json string? This is what I did, but it doesn't show alert message `` – abhi Jul 12 '18 at 17:14
  • You have to use _<%= grpAlphaInfoVOJSONString %>_ where _grpAlphaInfoVOJSONString_ is the name of variable having JSON string in controller – Aman Chhabra Jul 12 '18 at 17:16
  • `var aaData = <%= grpAlphaInfoVO %>;` is this it correct? sorry I am new to java and javascript and working as an intern, this is all new learning for me – abhi Jul 12 '18 at 17:17
  • __No__ _ grpAlphaInfoVO_ is ArrayList, you need to first convert into JSON string as shared in my answer – Aman Chhabra Jul 12 '18 at 17:20
  • yes i did convert it to json, just did not change the variable name, grpAlphaInfiVO is the json string – abhi Jul 12 '18 at 17:21
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/174902/discussion-between-abhi-and-aman-chhabra). – abhi Jul 12 '18 at 17:24
0

EDIT:

Solution for the problem:

$('#groupAlphaList').dataTable({
 "aaData": ${grpAlphaInfoVO} , 
 "aoColumns": [ { "mDataProp": "groupNumber" }, { "mDataProp": "groupName" } ]
});

Original answer:

Add a jQuery JavaScipt to call your controller:

http://api.jquery.com/jquery.ajax/

$(document).ready(function() {
    $.ajax({
       type: "GET",
       url: "/groupAlpha/search/groupNameValue",
       datatype: 'json',
       success: function (response) {
           grpAlphaInfoVO = response.grpAlphaInfoVO;
           $('#groupAlphaList').dataTable({
              "aaData": grpAlphaInfoVO
           });
       }
    });
});

@RequestMapping defines the end-point. It declares that server-side code has a method that can handle requests to the /groupAlpha/search/{groupName} URL. This is a declaration, not an actual call to the controller.

Any other application (Web browser, wget, Java applications, .NET application, scripts can call the endpoint declared with @RequestMapping).

Your JavaScript code needs to call the controller. JQuery, $.ajax function can be used to do this.

Pavel Molchanov
  • 2,299
  • 1
  • 19
  • 24
  • Yes, I understand that, but i want to get the data from the way i did it, I am getting the data from from server into a arraylist but I am not able to display the list in my jsp page. I know I can do that using ajax but it want to do in the way i did. I cannot share the whole code, I have the data in grpAlphaInfoVO which is a json string, if I do ${grpAlphaInfoVO} , I can see the data on my view but i want that data to use in javascript where i am trying to create jquery datatable – abhi Jul 12 '18 at 19:04
  • Then it should be as simple as: $('#groupAlphaList').dataTable({ data: ${grpAlphaInfoVO} }); – Pavel Molchanov Jul 12 '18 at 20:12
  • when I did ` $('#groupAlphaList').dataTable({ "aaData": ${grpAlphaInfoVO} }); });` I am getting an error alert as `DataTables warning (table id = 'groupAlphaList'): Requested unknown parameter '0' from the data source for row 0` – abhi Jul 12 '18 at 20:17
  • '$('#groupAlphaList').dataTable({ "aaData": ${grpAlphaInfoVO} , "aoColumns": [ { "mDataProp": "groupNumber" }, { "mDataProp": "groupName" },' this solved the problem – abhi Jul 13 '18 at 13:17
  • I am really glad that you was able to solve it yourself!. – Pavel Molchanov Jul 13 '18 at 13:31
  • I think you can post your own solution to your own problem :) – Pavel Molchanov Jul 13 '18 at 13:31
  • I added your solution from the comments to the answer. I don't want to delete my answer to keep valuable comments. – Pavel Molchanov Jul 13 '18 at 13:35
0

found the solution for my problem, we need to specify the columns as well when populating the data table:

Since I have two keys in my json that are groupNumber and groupName I need to include that in my datatable as well. Here is the sample code

$('#groupAlphaList').dataTable({
 "aaData": ${grpAlphaInfoVO} , 
 "aoColumns": [ { "mDataProp": "groupNumber" }, { "mDataProp": "groupName" } ]
});
abhi
  • 1,920
  • 6
  • 24
  • 27