null json在Ajax Call中返回

时间:2014-11-19 05:49:06

标签: java jquery ajax json servlets

我正在尝试使用ajax调用来检索数据,该调用使用servlet并传回JSON对象。 AJAX正在成功完成,但从servlet返回的JSON对象为null。但是当我在servlet中打印JSON对象时,它打印数据并且形成的JSON对象似乎是有效的。

{"orderObj":[{"FIRST_NAME":"John","LAST_NAME":"Mkay"}]}

HTML

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Dialog - Modal form</title>
<link rel="stylesheet"
    href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"
    type="text/javascript"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<style>
body {
    font-size: 62.5%;
}

h1 {
    font-size: 1.2em;
    margin: .6em 0;
}

div#orders-contain {
    width: 450px;
    margin: 30px 0;
}

div#orders-contain table {
    margin: 1em 0;
    border-collapse: collapse;
    width: 150%;
}

div#orders-contain table td, div#orders-contain table th {
    border: 1px solid #eee;
    padding: .6em 10px;
    text-align: left;
}
}
</style>
<script>
    $(document).ready(function() {
        $("#query-order").click(function(e) {
            dataString = "countryCode=";
            alert("on Load");
             $.ajax({
                    type: "POST",
                    url: "QueryOrder",
                    data: dataString,
                    dataType: "json",
                    success: function(
                        data) {
                        alert("I am in Success");
                        alert(data);
                    },
                    error: function(jqXHR,
                        textStatus,
                        errorThrown) {
                        alert("Error Return from Ajax");
                        alert(jqXHR
                            .getResponseHeader('Content-Type'));
                        alert(jqXHR.responseText);
                        alert(jqXHR);
                        alert(errorThrown);
                        alert(textStatus);
                    }
                }); //end of Ajax call
        }); // end of click function
    });
</script>
</head>
<body>
    <div id="orders-contain" class="ui-widget">
        <h1>Orders:</h1>
        <table id="Orders" class="ui-widget ui-widget-content">
            <thead>
                <tr class="ui-widget-header ">
                    <th>Order Number</th>
                    <th>Customer Number</th>
                    <th>First Name</th>
                    <th>Last Name</th>
                    <th>Date of Order</th>
                    <th>Address</th>
                    <th>Order Total</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td></td>
                    <td></td>
                    <td></td>
                    <td></td>
                    <td></td>
                    <td></td>
                    <td></td>
                </tr>
            </tbody>
        </table>
    </div>
    <button id="query-order">Query Orders</button>
</body>
</html>

的Servlet

package com.order.pkg;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.*;

public class QueryOrder extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public QueryOrder() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
           doPost(request,response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */ 
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json");        

        response.setHeader("Cache-control", "no-cache, no-store");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Expires", "-1");

        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type");
        response.setHeader("Access-Control-Max-Age", "86400"); 
        try {
            Class.forName("oracle.jdbc.OracleDriver");
            System.out.println("Driver loaded");

            String url = "jdbc:oracle:thin:@localhost:1521:xe";
            String user = "dbtest";
            String pwd = "dbtest";
            Connection DB_mobile_conn = DriverManager.getConnection(url, user,
                    pwd);
            System.out.println("Database Connect ok");

            String query = "select * from ORDER_HEADERS";

            ArrayList<Order> orderList = new ArrayList<Order>();


            if (query != null) {
                Statement query_stmt = DB_mobile_conn.createStatement();
                ResultSet query_rs = query_stmt.executeQuery(query);
                while (query_rs.next()) {
                    Order orderobj = new Order();
                    orderobj.setFIRST_NAME(query_rs.getString("FIRST_NAME").trim());
                    orderobj.setLAST_NAME(query_rs.getString("LAST_NAME").trim());
                    orderList.add(orderobj);
                }
                query_rs.close();
                query_stmt.close();
            }

            Gson gson = new Gson();
            JsonObject myObj = new JsonObject();
            JsonElement orderObj = gson.toJsonTree(orderList);
            myObj.add("orderObj", orderObj);
            System.out.println(myObj);      

            System.out.println(response.getContentType());              

        } catch (Exception exp) {
            System.out.println("Exception = " + exp);
        }
    }
}

请帮助我理解为什么返回null JSON。感谢您的帮助

2 个答案:

答案 0 :(得分:1)

这可能对您有所帮助

PrintWriter out = response.getWriter();
out.print(myObj);

不要使用System.out.println()它将在console.it上打印。不会发送response.to发送您需要使用PrintWritter的响应。

答案 1 :(得分:1)

您从未将 myObj 对象写入响应。 你必须使用:

response.getWriter().write(myObj.toString());