【问题标题】:Spring MVC data to jQuery jTableSpring MVC 数据到 jQuery jTable
【发布时间】:2016-10-30 23:30:23
【问题描述】:

我正在尝试将数据从 Spring mvc 应用程序发送到 jquery jtable 页面。

但是,我收到以下错误

An error occured while communicating to the server.

这是我的控制器方法。

@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";

}

这是我的 SampleJqueryTable JSP 页面。

    <%@ 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>

我正在使用 JSON Helper 类将数据发送到 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;
    }

}

对于视图,我使用 TilesViewResolver,这是我的 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>

【问题讨论】:

    标签: java spring-mvc jquery-jtable


    【解决方案1】:

    我能够解决这个问题。

    JSON 数据需要作为@ResponseBody 传递。我的错,我试图将它发送到 viewResolver 认为它能够理解如何翻译

        @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());
    }
    

    【讨论】:

      猜你喜欢
      • 2015-09-25
      • 1970-01-01
      • 1970-01-01
      • 2017-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-04
      相关资源
      最近更新 更多