Author Topic: Integeration with Spring MVC  (Read 6309 times)

bsolteam

  • Pro Deluxe
  • Full Member
  • *
  • Posts: 107
    • View Profile
Integeration with Spring MVC
« on: May 09, 2014, 01:05:27 pm »
Hi, Am trying to integrate spring mvc with paramgrid. But the json object is not returning to the paramgrid. This is the snippet i used in grid.
Code: [Select]
$(function () {
      var colM = [
        { title: "Vessel", align:'left',cls:'gre1',dataIndx:"vessel"},
{ title: "Std Voyage # 1 Net Results", align:'center',dataIndx:"voyage1"},
{ title: "Weightage of Std Voyage # 1  40%", align:'center',dataIndx:"voyage2"},
           ];
     
      var dataModel = {
          location: "remote",   
          sorting: "local",                     
          dataType: "JSON",
          method: "GET",
          url: "json",
          getData: function (dataJSON) {return { data: dataJSON.data };}
      }
 
       $("div#totalpp_tab_main").pqGrid({
          dataModel: dataModel,
          colModel: colM,
          wrap:false,hwrap:false,
          width: 1342,
                numberCell:false,
                editor:false,
editable: false,
                resizable:false,
sortable:false,
                scrollModel:{autoFit:true, theme:false},
                draggable:false,
collapsible: false,
showTitle: true,
showBottom:false,
      });
  });
Following code is used in controller class
Code: [Select]
@RequestMapping(value="/PoolB/json", method= RequestMethod.GET)
public String json(Model model,HttpServletRequest request)throws JSONException{
String  requrl=CommonUltility.getrequesturl(request.getRequestURL().toString());
System.out.println("U R in Json");
JSONObject obj = new JSONObject();

      obj.put("vessel","frejalupus");
      obj.put("voyage1",new Integer(100));
      obj.put("voyage2",new Integer(200));
     
      StringWriter out = new StringWriter();
      obj.write(out);
      String jsontext = out.toString();
     
      StringBuilder sb = new StringBuilder("{\"data\":");
      sb.append(jsontext);   
      sb.append("}");
      model.addAttribute("dataJSON", sb);
      System.out.print(sb.toString());
      return requrl;
}
My controller class giving the json obj like this
Code: [Select]
{"data":{"vessel":"frejalupus","voyage1":100,"voyage2":200}} What i need to do to get the json obj in param grid. In your demo section the code is available for asp.net and php. I can't find code for spring mvc. Would it be possible to provide a working example that uses Spring MVC?

Thanks in advance for your support!

paramvir

  • Administrator
  • Hero Member
  • *****
  • Posts: 6265
    • View Profile
Re: Integeration with Spring MVC
« Reply #1 on: May 09, 2014, 01:36:39 pm »
Your JSON format returned by controller should be in this format:

{"data":[{"vessel":"frejalupus","voyage1":100,"voyage2":200}]}

Check out for any errors in the browser console and put an alert in the getData callback to ensure grid is pointing to correct url.

Please let me know if you need any further assistance.

bsolteam

  • Pro Deluxe
  • Full Member
  • *
  • Posts: 107
    • View Profile
Re: Integeration with Spring MVC
« Reply #2 on: May 09, 2014, 02:38:36 pm »
Great. Thanks for Your instant Response. Now it is working.
« Last Edit: May 09, 2014, 02:46:45 pm by bsolteam »

bsolteam

  • Pro Deluxe
  • Full Member
  • *
  • Posts: 107
    • View Profile
Re: Integeration with Spring MVC
« Reply #3 on: May 12, 2014, 02:29:58 pm »
Hi, when I am giving the json object like this {"data":[{"vessel":"frejalupus","voyage1":100,"voyage2":200}]} from spring mvc The grid display the data's. But when am giving in this format
Code: [Select]
{"data":[{"vessel":"FrejaLupus","voyage1":3052,"voyage2":7121},{"vessel":"Targale","voyage1":2056,"voyage2":5466},{"vessel":"StxAce6","voyage1":6876,"voyage2":78956},{"vessel":"StiTopaz","voyage1":5688,"voyage2":8767},]} it will not display the data. Why it is not showing. What am doing wrong. I need a correct json object format.

Thanks in advance.

paramvir

  • Administrator
  • Hero Member
  • *****
  • Posts: 6265
    • View Profile
Re: Integeration with Spring MVC
« Reply #4 on: May 12, 2014, 02:41:48 pm »
you have trailing comma at the end

},]}

which should be

}]}

bsolteam

  • Pro Deluxe
  • Full Member
  • *
  • Posts: 107
    • View Profile
Re: Integeration with Spring MVC
« Reply #5 on: May 15, 2014, 07:59:14 pm »
Hi, Am trying to add new row. Now I can add row and if I added the data's in that row it is not reaching my controller class. After I put alert in the error function like this
Code: [Select]
alert("error: "+data.Vessel+" status: "+status+" er:"+er); In the alert it shows error:undefined status:error er:Bad Request.  Here is my code snippet.

Code: [Select]
$(function () {
    var ajaxObj = {
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        type: "POST",
        async: true,
        beforeSend: function (jqXHR, settings) {               
            $grid.pqGrid("showLoading");
        }
    };
 
    //called when accept changes button is clicked.
    function acceptChanges() {
        //attempt to save editing cell.
        //debugger;
        if ($grid.pqGrid("saveEditCell") === false) {
            return false;
        }
 
        var isDirty = $grid.pqGrid("isDirty");
        if (isDirty) {
            //validate the new added rows.               
            var addList = $grid.pqGrid("getChanges").addList;
            for (var i = 0; i < addList.length; i++) {
                var rowData = addList[i];
                var isValid = $grid.pqGrid("isValid", { "rowData": rowData }).valid;
                if (!isValid) {
                    return;
                }
            }
            var changes = $grid.pqGrid("getChanges", { format: "byVal" }),
                addList = changes.addList,
                updateList = changes.updateList,
                deleteList = changes.deleteList;
 
            if (addList.length) {
                $.ajax($.extend({}, ajaxObj, {
                    url: "${pageContext.request.contextPath}/PoolB/person",   
                    data: JSON.stringify(addList),
                    success: function (rows) {
                        $grid.pqGrid("commit", { type: 'add', rows: rows });
                    },
                    complete: function () {
                        $grid.pqGrid("hideLoading");
                        $grid.pqGrid("rollback", { type: 'add' });
                    },
                    error:function(data,status,er) {
                    alert("error: "+data.Vessel+" status: "+status+" er:"+er);
                },
                }));
            }
           
         
            if (updateList.length) {
                $.ajax($.extend({}, ajaxObj, {
                    url: "/pro/products/updateList",
                    data: JSON.stringify(updateList),
                    //data: { "updateList": JSON.stringify(updateList) },
                    success: function (rows) {
                        //debugger;
                        $grid.pqGrid("commit", { type: 'update', rows: rows });
                    },
                    complete: function () {
                        $grid.pqGrid("hideLoading");
                        $grid.pqGrid("rollback", { type: 'update' });
                    }
                }));
            }
            if (deleteList.length) {
                $.ajax($.extend({}, ajaxObj, {
                    url: "/pro/products/deleteList",
                    data: JSON.stringify(deleteList),
                    success: function (rows) {
                        $grid.pqGrid("commit", { type: 'delete', rows: rows });
                    },
                    complete: function () {
                        $grid.pqGrid("hideLoading");
                        $grid.pqGrid("rollback", { type: 'delete' });
                    }
                }));
            }
        }
    }
    var obj = {
        width: 920,
        height: 400,
        wrap: false,
        hwrap: false,
        resizable: true,
        rowBorders: false,
        numberCell: { show: false },
        track: true, //to turn on the track changes.
        flexHeight: true,
        toolbar: {
            items: [
                { type: 'button', icon: 'ui-icon-plus', label: 'New Product', listeners: [
                    { "click": function (evt, ui) {
                        //append empty row at the end.                           
                        var rowData = { UnitPrice: 0, Discontinued: false }; //empty row
                        var rowIndx = $grid.pqGrid("addRow", { rowData: rowData });
                        $grid.pqGrid("goToPage", { rowIndx: rowIndx });
                        $grid.pqGrid("editFirstCellInRow", { rowIndx: rowIndx });
                    }
                    }
                ]
                },
                { type: 'button', icon: 'ui-icon-disk', label: 'Accept Changes', style: 'margin:0px 5px;', listeners: [
                    { "click": function (evt, ui) {
                        acceptChanges();
                    }
                    }
                ]
                },
                { type: 'button', icon: 'ui-icon-cancel', label: 'Reject Changes', listeners: [
                    { "click": function (evt, ui) {
                        $grid.pqGrid("rollback");
                    }
                    }
                ]
                },
                { type: 'separator' },
                { type: 'button', icon: 'ui-icon-cart', label: 'Get Changes', style: 'margin:0px 5px;', listeners: [
                    { "click": function (evt, ui) {
                        var changes = $grid.pqGrid("getChanges");
                        try {
                            console.log(changes);
                        }
                        catch (ex) { }
                        alert("Please see the log of changes in your browser console.");
                    }
                    }
                ]
                }
            ]
        },
        scrollModel: {
            autoFit: true
        },
        selectionModel: {
            type: ''
        },
        hoverMode: 'cell',
        editModel: {
            saveKey: $.ui.keyCode.ENTER
        },
        title: "<b>Batch Editing</b>",
 
        colModel: [
{ title: "Vessel", align:'left',cls:'gre1',dataIndx:"Vessel",halign:'center',dataType: "string"},
{ title: "Std Voyage # 1 Net Results", align:'center',dataIndx:"Stdvoyage1",dataType: "integer"},
{ title: "Weightage of Std Voyage # 1  40%", align:'center',dataIndx:"Weightage1",dataType: "integer"},
{ title: "Std Voyage # 2 Net Results", align:'center',dataIndx:"Stdvoyage2",dataType: "integer"},
{ title: "Weightage of Std Voyage # 2  40%", align:'center',dataIndx:"Weightage2",dataType: "integer"},
{ title: "TotalIncome", align:'center',dataIndx:"TotalIncome"},
        ],
        pageModel: { type: "local" },
        dataModel: {               
            dataType: "JSON",
            location: "remote",
            recIndx: "ProductID",
            url: "json",
            getData: function (response) {
                return { data: response.data };
            }
        },
        //save the cell when cell loses focus.
        quitEditMode: function (evt, ui) {               
            if (evt.keyCode != $.ui.keyCode.ESCAPE) {
                $grid.pqGrid("saveEditCell");
            }
        },
        refresh: function () {
            $("#grid_editing").find("button.delete_btn").button({ icons: { primary: 'ui-icon-scissors'} })
            .unbind("click")
            .bind("click", function (evt) {
                var $tr = $(this).closest("tr");
                var obj = $grid.pqGrid("getRowIndx", { $tr: $tr });
                var rowIndx = obj.rowIndx;
                $grid.pqGrid("addClass", { rowIndx: rowIndx, cls: 'pq-row-delete' });
 
                var ans = window.confirm("Are you sure to delete row No " + (rowIndx + 1) + "?");
 
                if (ans) {
                    $grid.pqGrid("deleteRow", { rowIndx: rowIndx, effect: true, complete: function () {
                        $grid.pqGrid("removeClass", { rowIndx: rowIndx, cls: 'pq-row-delete' });
                    }
                    });
                }
                else {
                    $grid.pqGrid("removeClass", { rowIndx: rowIndx, cls: 'pq-row-delete' });
                }
            });
        },
        cellBeforeSave: function (evt, ui) {
            var isValid = $grid.pqGrid("isValid", ui);
            if (!isValid.valid) {
                evt.preventDefault();
                return false;
            }
        }
    };
    var $grid = $("#totalpp_tab_main").pqGrid(obj);
});

I used the following code for checking purpose in the addList.
Code: [Select]
if (addList.length) { 
            var search = {
              "name" : "bhanu",
              "id" :"2"
           };
            $.ajax({
          url: "${pageContext.request.contextPath}/PoolB/person", 
              type: 'POST',
              dataType: 'json',
              data: JSON.stringify(search),
              contentType: 'application/json',
              mimeType: 'application/json',
              success: function(data) {
                  alert(data.id + " " + data.name);
              },
              error:function(data,status,er) {
                  alert("error: "+data.Vessel+" status: "+status+" er:"+er);
              }
          });
            }

This code is working fine and it is reaching the controller class and am getting the value. I don't know what am doing wrong or else what am missing.
Thanks in advance.
« Last Edit: May 15, 2014, 08:02:20 pm by bsolteam »

paramvir

  • Administrator
  • Hero Member
  • *****
  • Posts: 6265
    • View Profile
Re: Integeration with Spring MVC
« Reply #6 on: May 16, 2014, 09:52:47 am »
addList is an array, so check with this:

var search = [{
         "name" : "bhanu",
         "id" :"2"
   }];

If it doesn't work, then try it without JSON.stringify
« Last Edit: May 16, 2014, 09:55:41 am by paramquery »