Search code examples
javaspring-mvcjquery-jtable

Spring MVC data to jQuery jTable


I am trying to send data from Spring mvc application to jquery jtable page.

However, I get the following error

An error occured while communicating to the server.

Here is my Controller method.

@RequestMapping("/sampleJqueryTable")
public Object sampleJqueryTable(HttpServletRequest request,
        HttpServletResponse response) throws IOException
{
    List<FinalAbendData> studentList2 = null;
    System.out.println("This will be printed two times... if my guess is correct 1");
    String action = request.getParameter("action");
    if ( action != null) 
    {
            studentList2 = new ArrayList<FinalAbendData>();

            if(action.contains("list4"))
            {
                System.out.println("inside action 4");                        
                try
                {                                                                       
                // Add data to Student list
                studentList2.add(new FinalAbendData("Haripriya","Haripriya", "Haripriya", "IT", "xyz@xyz.com"));
                studentList2.add(new FinalAbendData("Haripriya","Haripriya", "Dinesh", "ECE", "xyz@gmail.com"));
                studentList2.add(new FinalAbendData("Haripriya","Haripriya", "Prabhu", "MECH", "abc@gmail.com"));
                studentList2.add(new FinalAbendData("Haripriya","Haripriya", "Badru", "ECE", "efg@gmail.com"));
                studentList2.add(new FinalAbendData("Haripriya","Haripriya", "Lahir nisha", "CSC", "xyz@gmail.com"));
                studentList2.add(new FinalAbendData("Haripriya","Haripriya", "Nilafar nisha", "CSC", "123@gmail.com"));
                studentList2.add(new FinalAbendData("Haripriya","Haripriya", "Jamil", "ECE", "789@gmail.com"));
                studentList2.add(new FinalAbendData("Haripriya","Haripriya", "Mahes", "ECE", "123@gmail.com"));
                studentList2.add(new FinalAbendData("Haripriya","Haripriya", "Lourde", "IT", "xyz@gmail.com"));



                System.out.println(new JsonJtableResponse().ok(studentList2).toString());

                return new JsonJtableResponse().ok(studentList2);
                }
                catch(Exception ex){
                    // Don't forget to send Error message to jtable
                }
            }

            }   

    return "sampleJqueryTable";

}

Here is my SampleJqueryTable JSP PAGE.

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>jQuery jTable Setup in java</title>
<!-- jTable Metro styles. -->
<link href="js/jtable.css" rel="stylesheet"
    type="text/css" />
<!-- <link href="css/jquery-ui-1.10.3.custom.css" rel="stylesheet" type="text/css" /> -->
<!-- jTable script file. -->
<script src="js/jquery-1.8.2.min.js" type="text/javascript"></script>
<script src="js/jquery-ui-1.10.3.custom.js" type="text/javascript"></script>
<script src="js/jquery.jtable.js" type="text/javascript"></script>
<script type="text/javascript">
    $(document)
            .ready(
                    function() {

                        $('#StudentTableContainer')
                                .jtable(
                                        {
                                            title : 'Transaction Abends',
                                            paging : true, //Enable paging
                                            sorting : true, //Enable sorting
                                            defaultSorting : 'Name ASC',
                                            //openChildAsAccordion: true, //Enable this line to show child tabes as accordion style
                                            actions : {
                                                listAction : 'sampleJqueryTable?action=list4'
                                            },
                                            fields : {

                                                programName : {
                                                    title : 'Program Name',
                                                    width : '10%',
                                                    key : true,
                                                    list : true,
                                                    create : true
                                                },
                                                abendCode : {
                                                    title : 'Abend Code',
                                                    width : '10%',
                                                    edit : false
                                                },
                                                startDate : {
                                                    title : 'Start Date',
                                                    width : '10%',
                                                    edit : true
                                                },
                                                transCode : {
                                                    title : 'Transaction Code',
                                                    width : '10%',
                                                    edit : true
                                                },
                                                releaseDate : {
                                                    title : 'Release Date',
                                                    width : '10%',
                                                    edit : true
                                                }
                                            }
                                        });

                        //Load student list from server
                        $('#StudentTableContainer').jtable('load');

                    });
</script>


<style>



</style>

</head>
<body>

<br>
<br>
<br>
    <div style="text-align: center;">
        <div id="StudentTableContainer"></div>
    </div>

</body>
</html>

I am using a JSON Helper class to send data to jquery jtable

public class JsonJtableResponse implements Serializable {

    private static final long serialVersionUID = 8046209322844760834L;

    /**
     * The map to hold the jtable response, this will be sent as json by @ResponseBody.
     * Example: {"Result":"ERROR","Message":"Some error message"}
     */
    private Map<String, Object> jsonResponseMap;

    private static final String KEY_RESULT = "Result";
    private static final String RESULT_OK = "OK";
    private static final String RESULT_ERROR = "ERROR";
    private static final String RESULT_ERROR_SILENT = "ERROR_SILENT";

    private static final String KEY_RECORD = "Record"; //if result ok and insert
    private static final String KEY_RECORDS = "Records"; //if result ok and list
    private static final String KEY_MESSAGE = "Message"; //if result error

    public JsonJtableResponse() {
        jsonResponseMap = new HashMap<String, Object>();
    }

    /**
     * This can be used by any jtable action to indicate the operation failed and provide the error message. This
     * error message will be displayed in a popup and the table will show the default 'no data found' row.
     *
     * @param errorMessage the cause of the error
     * @return the json respose object with result error and an error message
     */
    public JsonJtableResponse error(String errorMessage) {
        jsonResponseMap.put(KEY_RESULT, RESULT_ERROR);
        jsonResponseMap.put(KEY_MESSAGE, errorMessage);
        return this;
    }

    /**
     * This can be used by any jtable action to indicate the operation failed and provide the error message in the
     * row of the table. The popup message is supressed with this method.
     *
     * @param errorMessage the cause of the error
     * @return the json respose object with result error and an error message
     */
    public JsonJtableResponse errorNoPopup(String errorMessage) {
        jsonResponseMap.put(KEY_RESULT, RESULT_ERROR_SILENT);
        jsonResponseMap.put(KEY_MESSAGE, errorMessage);
        return this;
    }

    /**
     * This can be used by any jtable action to display a spring binding result error.
     *
     * @param errorMessage the cause of the error
     * @return the json respose object with result error and an error message
     */
    public JsonJtableResponse error(List<ObjectError> errorList) {
        jsonResponseMap.put(KEY_RESULT, RESULT_ERROR);
        StringBuilder sb = new StringBuilder();
        for (ObjectError err : errorList) {
            sb.append(err.getDefaultMessage()).append("");
        }
        jsonResponseMap.put(KEY_MESSAGE, sb.toString());
        return this;
    }

    /**
     * This can be used by createAction to indicate the operation was successful, the new
     * object must be passed in to this method.
     *
     * @param result the newly inserted object to add to the table
     * @return the json respose object with result of 'ok'
     */
    public JsonJtableResponse ok(Object result) {
        jsonResponseMap.put(KEY_RESULT, RESULT_OK);
        jsonResponseMap.put(KEY_RECORD, result);
        System.out.println("Message invoked");
        return this;
    }

    /**
     * This can be used by listAction to indicate the operation was successful, and the list of object to
     * be displayed by the table are passed in.
     *
     * @param resultList the list to diaplay in the jtable
     * @return the json respose object with result of 'ok'
     */
    public JsonJtableResponse ok(List<? extends Object> resultList) {
        jsonResponseMap.put(KEY_RESULT, RESULT_OK);
        jsonResponseMap.put(KEY_RECORDS, resultList);
        for(Object obj : resultList)
        {
            System.out.println(obj);
        }
        return this;
    }

    /**
     * This can be used by the deleteAction and updateAction to indicate the operation
     * was successful.
     *
     * @return the json respose object with result of 'ok'
     */
    public JsonJtableResponse ok() {
        jsonResponseMap.put(KEY_RESULT, RESULT_OK);
        return this;
    }

    @JsonValue
    public Map<String, Object> getJsonResponseMap() {
        return jsonResponseMap;
    }

}

For views, I am using TilesViewResolver and here is my POM.XML

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.4.1</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.4.1.1</version>
</dependency>

Solution

  • I was able to fix this issue.

    JSON data needs to be passed as a @ResponseBody. My bad, I was trying to send it to the viewResolver thinking that it will be able to understand how to translate

        @RequestMapping("/sampleJqueryTable")
    public Object sampleJqueryTable(HttpServletRequest request,
            HttpServletResponse response) throws IOException
    {
    
    
        return "sampleJqueryTable";
        //return new Json("OK",studentList2,studentList2.size());
    
    }
    
    
    
        @RequestMapping(value = "/sampleJqueryTables/list")
    @ResponseBody
    public JsonResult sampleJqueryList(HttpServletRequest request,
            HttpServletResponse response)
    {
    
        HashMap<String, Object> JSONROOT = new HashMap<String, Object>();
        List<FinalAbendData> studentList2 = null;
    
        try
        {         
        studentList2 = new ArrayList<FinalAbendData>();
        // Add data to Student list
        studentList2.add(new FinalAbendData("Haripriya","Haripriya", "Haripriya", "IT", "xyz@xyz.com"));
        studentList2.add(new FinalAbendData("Haripriya","Haripriya", "Dinesh", "ECE", "xyz@gmail.com"));
        studentList2.add(new FinalAbendData("Haripriya","Haripriya", "Prabhu", "MECH", "abc@gmail.com"));
        studentList2.add(new FinalAbendData("Haripriya","Haripriya", "Badru", "ECE", "efg@gmail.com"));
        studentList2.add(new FinalAbendData("Haripriya","Haripriya", "Lahir nisha", "CSC", "xyz@gmail.com"));
        studentList2.add(new FinalAbendData("Haripriya","Haripriya", "Nilafar nisha", "CSC", "123@gmail.com"));
        studentList2.add(new FinalAbendData("Haripriya","Haripriya", "Jamil", "ECE", "789@gmail.com"));
        studentList2.add(new FinalAbendData("Haripriya","Haripriya", "Mahes", "ECE", "123@gmail.com"));
        studentList2.add(new FinalAbendData("Haripriya","Haripriya", "Lourde", "IT", "xyz@gmail.com"));
    
    
    
        System.out.println(new JsonJtableResponse().ok(studentList2).toString());
    
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        response.setContentType("application/json");
    
        JSONROOT.put("Result", "OK");
        JSONROOT.put("Records", studentList2);
    
        // Convert Java Object to Json
        String jsonArray = gson.toJson(JSONROOT);
        System.out.println(jsonArray);
    
        return new Json("OK",studentList2,studentList2.size());
        //return new JsonJtableResponse().ok(studentList2);
        //return jsonArray;
        }
        catch(Exception ex){
            // Don't forget to send Error message to jtable
        }
    
        return new Json("OK",studentList2,studentList2.size());
    }