This is a migrated thread and some comments may be shown as answers.

Datasource, using JSP, Javascript and Java action

16 Answers 381 Views
Data Source
This is a migrated thread and some comments may be shown as answers.
This question is locked. New answers and comments are not allowed.
Leo
Top achievements
Rank 1
Leo asked on 17 Dec 2011, 09:35 PM

I was wondering if any one had a working example of loading data onto a grid using a Java action?

The following is a code snippet of something I did a while back using DHTMLX Grid and Dojo.

So, inside my JSP I call the Java action that returns the data in XML format like so:

<script>
    var mysubgrid;
    mysubgrid = new dhtmlXGridObject('gridbox'); 
    function doInitSubGrid(rowID)
    {
        var leadsSourceRecId = rowID ;
        var URL = "" ;
        var query = "pLeadsSourceRecId=" + leadsSourceRecId ;
 
        mysubgrid = new dhtmlXGridObject('mysubgrid_container');
        mysubgrid.setImagePath("../dhx/codebase/imgs/");  
        mysubgrid.setHeader("LEADS MASTER LIST,#cspan,#cspan,#cspan,#cspan,#cspan") ;                                                      
        mysubgrid.attachHeader("Status, Source, Date, Name, Email, Home Phone");
        mysubgrid.attachHeader("#text_filter,#text_filter,#text_filter,#text_filter,#text_filter,#text_filter");                                               
        mysubgrid.setInitWidths("80,100,100,170,170,100");
        //mysubgrid.setColAlign("left,left,left,left,left,left")
        mysubgrid.setSkin("light");
        mysubgrid.setColSorting("str,str,str,str,str,str");
        mysubgrid.setColTypes("ro,ro,ro,ro,ro,ro");
        mysubgrid.attachEvent("onRowSelect",doOnRowSelectedSubGrid);
        mysubgrid.init();
 
        // HERE IS WHERE I CALL MY JAVA ACTION: GetLeadsGridDataStr.action
           // I PASS A PARAMETER CALLED pLeadsSourceId
        mysubgrid.loadXML("GetLeadsGridDataStr.action?pLeadsSourceRecId=" + leadsSourceRecId) ;  
    }
</script>

The data is then rendered on the DHTMLX Grid.

Does Anybody have an example like this one using Kendo?

 

16 Answers, 1 is accepted

Sort by
0
Nikolay Rusev
Telerik team
answered on 19 Dec 2011, 01:27 PM
Hello Leo,

The Grid widget uses a DataSource component in order to retrieve and manipulate data. The DataSource is responsible to retrieve the data from local/remote source. You can find more details on what DataSource is and how it operates in the following articles:
http://www.kendoui.com/documentation/framework/datasource/overview.aspx
http://demos.kendoui.com/web/datasource/remote-data.html

To your question - you need to setup the dataSource of the Grid in order to retrieve data from the view. The view on the other hand must return a valid JSON.
http://demos.kendoui.com/web/grid/remote-data.html

That all you need in order to provide the data from any server technology.

Best wishes,
Nikolay Rusev
the Telerik team
Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
0
Leo
Top achievements
Rank 1
answered on 20 Dec 2011, 02:47 AM

Hi Nikolay,

I’m working with one of the examples provided by the KendoUI download to try to get it to work with Java.

I create a Java class called: GetDataGrid.class

If invoked through the URL, this Java class returns the following string:

([{"ProductID":1,"ProductName":"Chai","UnitPrice":18,"UnitsInStock":39,"Discontinued":false},{"ProductID":2,"ProductName":"Chang","UnitPrice":19,"UnitsInStock":17,"Discontinued":false},{"ProductID":3,"ProductName":"Aniseed Syrup","UnitPrice":10,"UnitsInStock":13,"Discontinued":false}])

I then modified the JavaScript and replaced /Products with /GetDataGrid.action.

<script>
    $(document).ready(function () {
        var crudServiceBaseUrl = "",
            dataSource = new kendo.data.DataSource({
                transport: {
                    read:  {
                       // Modified from /Products to /GetDataGrid.action
                        url: crudServiceBaseUrl + "/GetDataGrid.action",
                        dataType: "jsonp"
                    },
                    update: {
                        url: crudServiceBaseUrl + "/Products/Update",
                        dataType: "jsonp"
                    },
                    destroy: {
                        url: crudServiceBaseUrl + "/Products/Destroy",
                        dataType: "jsonp"
                    },
                    create: {
                        url: crudServiceBaseUrl + "/Products/Create",
                        dataType: "jsonp"
                    },
                    parameterMap: function(options, operation) {
                        if (operation !== "read" && options.models) {
                            return {models: kendo.stringify(options.models)};
                        }
                    }
                },
                batch: true,
                pageSize: 30,
                schema: {
                    model: {
                        id: "ProductID",
                        fields: {
                            ProductID: { editable: false, nullable: true },
                            ProductName: { validation: { required: true } },
                            UnitPrice: { type: "number", validation: { required: true, min: 1} },
                            Discontinued: { type: "boolean" },
                            UnitsInStock: { type: "number", validation: { min: 0, required: true } }
                        }
                    }
                }
            });
 
        $("#grid").kendoGrid({
            dataSource: dataSource,
            navigatable: true,
            pageable: true,
            height: 400,
            toolbar: ["create", "save", "cancel"],
            columns: [
                "ProductName",
                { field: "UnitPrice", format: "{0:c}", width: "150px" },
                { field: "UnitsInStock", width: "150px" },
                { field: "Discontinued", width: "100px" },
                { command: "destroy", title: " ", width: "110px" }],
            editable: true
        });
    });
</script>

However, when I run the HTML page the data does not load on the grid.

What am I doing wrong?























0
Nikolay Rusev
Telerik team
answered on 20 Dec 2011, 12:54 PM
Hello Leo,

As the response is in the same domain and is JSON not JSONP you will have to remove the dataType: "jsonp" in order to bind the Grid.

The response seems to be a valid JSON so it should bind to the Grid.

For your convenience I am attaching sample app built with Play framework that demonstrates how to bind Kendo Grid. The view resides in /app/views/application/index.html
and the controller in /app/controllers/Application.java

Regards,
Nikolay Rusev
the Telerik team
Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
0
Leo
Top achievements
Rank 1
answered on 20 Dec 2011, 05:33 PM

Hi Nikolay,

Got it working – thank you.

0
Leo
Top achievements
Rank 1
answered on 20 Dec 2011, 07:25 PM

Ok, I’m posting this for anyone using Java  EE to build the server side components.

I used the following code to populate a data grid:

So, my HTML page contains the following:

<script>
    $(document).ready(function () {
        var crudServiceBaseUrl = "/site",
            dataSource = new kendo.data.DataSource({
                transport: {
                    read:  {
                        url: crudServiceBaseUrl + "/GetDataGrid.action",
                        dataType: "json"
                    },
                    update: {
                        url: crudServiceBaseUrl + "/Products/Update",
                        dataType: "jsonp"
                    },
                    destroy: {
                        url: crudServiceBaseUrl + "/Products/Destroy",
                        dataType: "jsonp"
                    },
                    create: {
                        url: crudServiceBaseUrl + "/Products/Create",
                        dataType: "jsonp"
                    },
                    parameterMap: function(options, operation) {
                        if (operation !== "read" && options.models) {
                            return {models: kendo.stringify(options.models)};
                        }
                    }
                },
                batch: true,
                pageSize: 30,
                schema: {
                    model: {
                        id: "ProductID",
                        fields: {
                            ProductID: { editable: false, nullable: true },
                            ProductName: { validation: { required: true } },
                            UnitPrice: { type: "number", validation: { required: true, min: 1} },
                            Discontinued: { type: "boolean" },
                            UnitsInStock: { type: "number", validation: { min: 0, required: true } }
                        }
                    }
                }
            });
 
        $("#grid").kendoGrid({
            dataSource: dataSource,
            navigatable: true,
            pageable: true,
            height: 400,
            toolbar: ["create", "save", "cancel"],
            columns: [
                "ProductName",
                { field: "UnitPrice", format: "{0:c}", width: "150px" },
                { field: "UnitsInStock", width: "150px" },
                { field: "Discontinued", width: "100px" },
                { command: "destroy", title: " ", width: "110px" }],
            editable: true
        });
    });
</script>
 
 

My Java class (GetDataGrid .java), contains the following:

 

package com.kendoui;
 
import org.mentawai.core.*;
import org.mentawai.ajax.*;
import org.json.JSONObject;
 
public class GetDataGrid extends BaseAction
{
    // ______________________________________________________
    // START DECLARE NECESSARY FIELDS
    // END DECLARE NECESSARY FIELDS
    // ______________________________________________________  
     
    public String execute() throws Exception
    {
        StringBuffer jsonBuf = new StringBuffer() ;
         
        JSONObject jsonObj = new JSONObject();
        jsonObj.put("ProductID",new Integer(3));
        jsonObj.put("ProductName","Toshiba");
        jsonObj.put("UnitPrice",new Double(255.00));
        jsonObj.put("UnitsInStock",new Integer(100));
        jsonObj.put("Discontinued",false);
        jsonBuf.append(jsonObj.toString()) ;
        jsonObj.isNull(null) ;
         
        jsonObj.put("ProductID",new Integer(100));
        jsonObj.put("ProductName","Acer");
        jsonObj.put("UnitPrice",new Double(300.00));
        jsonObj.put("UnitsInStock",new Integer(13));
        jsonObj.put("Discontinued",false);
        jsonBuf.append(",").append(jsonObj.toString()) ;       
        jsonObj.isNull(null) ;
         
        jsonObj.put("ProductID",new Integer(88));
        jsonObj.put("ProductName","Dell");
        jsonObj.put("UnitPrice",new Double(475.00));
        jsonObj.put("UnitsInStock",new Integer(135));
        jsonObj.put("Discontinued",false);
        jsonBuf.append(",").append(jsonObj.toString()) ;       
         
        output.setValue(AjaxConsequence.OBJECT, "[" + jsonBuf.toString() + "]");
        return SUCCESS;
    }                  
}

This works beautifully but obviously, its very simple. Here I’m using static data but in a real life scenario, one would be pulling data from another source such as MySQL. 


Enjoy.

 

 

 

0
Daniel
Top achievements
Rank 1
answered on 10 Jan 2012, 12:26 PM
 Leo , Thanks  for the  coding, but i got an error in the lineoutput.setValue(AjaxConsequence.OBJECT, "[" + jsonBuf.toString() + "]");  Could u help me to clear the error
0
Daniel
Top achievements
Rank 1
answered on 11 Jan 2012, 07:16 AM
Hi  Nikolay,
                      I am  working on the kendo grid. i am trying to fetch the data from database using java, I got the value on the java , bot it does not print the value in grid. I am using the  PrintWriter to print  the values and my code and the java result are
 
   
<div id="movies-container" class="k-widget k-header k-menu-vertical">
        <ul id="movies"></ul>
    </div>
    <script>
        jQuery(document).ready(function(){
            var dataSource = new kendo.data.DataSource({
                    transport: {
                     read:{
                         url:'ajaxClientload.action',
                         dataType: "json"
                         }
                 },
                 batch: true,
                 pageSize: 30,
                 schema:{
                     model:{
                         fields:{
                             FirstName:{type:"string"}
                         }
                     }
                     
                 }
            });
            dataSource.read();   
             
             $("#movies").kendoGrid({
                    dataSource: dataSource,
                    navigatable: true,
                    pageable: true,
                    height: 400,
                    toolbar: ["create", "save", "cancel"],
                    columns: [
                        { field: "FirstName", width: "150px" }],
                    editable: true
                });
        });
     
    </script>

{"FirstName":"James"}
0
Nikolay Rusev
Telerik team
answered on 11 Jan 2012, 08:39 AM
Hello Daniel,

All you need to bind the Grid is to return valid JSON from server, i.e from 'ajaxClientload.action'.

All the best,
Nikolay Rusev
the Telerik team
Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
0
Daniel
Top achievements
Rank 1
answered on 11 Jan 2012, 09:52 AM
Hello Nikolay,
              Thanks for your reply. The server returns the valid json, I don't know what i am missing i send a code to you, Can u help me

public String execute() throws Exception
    {
        StringBuffer jsonbuff = new StringBuffer();
         
        JSONObject jsonObj = new JSONObject();
         
        jsonObj.put("FirstName", "James");
            
        print(jsonObj.toString());
        System.out.println("sample " + jsonObj.toString());
        return SUCCESS;
    }
 
private boolean printed;
    private PrintWriter out;
 
  protected void print(String text)
        {
            printed = true;
            getResponse().setContentType("application/json");
            getOut().print(String.valueOf(text));
        }
         
        public PrintWriter getOut()
        {
            if(out == null)
            {
                try
                {
                    setOut(getResponse().getWriter());
                }
                catch(IOException e)
                {
                   // LogHandler.error(this, e);
                }
            }
            return out;
        }
        

0
Nikolay Rusev
Telerik team
answered on 11 Jan 2012, 10:11 AM
Hello Daniel,

The data that is returned must ba e collection. I see a single item returned from your action method ( {"FirstName":"James"} ).


All the best,
Nikolay Rusev
the Telerik team
Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
0
Daniel
Top achievements
Rank 1
answered on 11 Jan 2012, 11:29 AM
Hai Nikolay,

        Thanks for ur reply. I got it  it works fine. 
0
Leo
Top achievements
Rank 1
answered on 11 Jan 2012, 02:55 PM
Hi Daniel,

You did not specify the error you were getting but I have an idea of what it might be.

In my Java app, I’m using the Menta MVC. You’ll notice the following packages:

import org.mentawai.core.*;
import org.mentawai.ajax.*;


So, if you use the following in your Java class you will get an error:

output.setValue(AjaxConsequence.OBJECT, "[" + jsonBuf.toString() + "]");


You must either use the Menta API, look here:



Or return your value differently.
0
Daniel
Top achievements
Rank 1
answered on 12 Jan 2012, 04:51 AM
Hai Leo,
       Thanks for your reply and code , It's working fine.
0
miao
Top achievements
Rank 1
answered on 14 Mar 2013, 03:21 PM
read is ok!  But when is update,how to do.Can you tell me the how to write the the code o action! I don't know how to request the parameters. I want to knw!!!!!
0
miao
Top achievements
Rank 1
answered on 14 Mar 2013, 03:24 PM
My English is not very good. I want to say how to update the operating action code on how to modify parameters.
0
Daniele
Top achievements
Rank 1
answered on 25 Mar 2013, 09:28 AM
And to delete a row with framework play?
I can catch the event in java, but I can't find record ID
Tags
Data Source
Asked by
Leo
Top achievements
Rank 1
Answers by
Nikolay Rusev
Telerik team
Leo
Top achievements
Rank 1
Daniel
Top achievements
Rank 1
miao
Top achievements
Rank 1
Daniele
Top achievements
Rank 1
Share this question
or