从mongodb java获取日期到jsp显示为null

时间:2016-11-07 08:38:28

标签: java mongodb jsp mongodb-query mongodb-java

setter和getter是Date类型 这是我的连接代码:

    public void connectToDb() {
        try {
            MongoClient mongoClient = new MongoClient("localhost", 27017);
            DB db = mongoClient.getDB("bookingSystem");
            bookingsCol = db.getCollection("bookings");
        } catch (Exception e) {
            System.err.println(e.getClass().getName() + ": " + e.getMessage());
         }
      }

获取mongo中值的代码:

    "_id" : ObjectId("5820145df23fc5ccffd52155"),
    "userID" : "1B",
    "bookings" : [
                    {
                    "startDateTime" : ISODate("2017-08-22T08:00:00Z")
                    }
                  ]
    public Booking getBooking(int bookingID, String userID) {
        connectToDb();
        BasicDBObject query = new BasicDBObject();
        query.put("bookings.bookingID", bookingID);
        DBCursor cursor = bookingsCol.find(query);
        while (cursor.hasNext()) {
        DBObject theObj = cursor.next();

        BasicDBList bookingsList = (BasicDBList) theObj.get("bookings");
        for (int i = 0; i < bookingsList.size(); i++) {
            BasicDBObject bookingObj = (BasicDBObject) bookingsList.get(i);
            Date startDateTime = bookingObj.getDate("startDateTime");
            booking.setStartDateTime(startDateTime);
        }
    }
    return booking;
   }

当我返回值时,收到格式:Fri Sep 22 12:00:00 MUT 2017这是好的,因为它匹配我的输入但是当我从jsp预订.getStartDateTime()时。对于日期,它为null,但大小为1.

现在在jsp中,getListOfBooking()是我的预订类中的一个函数,它返回一个对象数组,这就是为什么我让.size()知道它是否有值。我尝试用字符串来做它,然而它的工作日期显示错误。

        <%
        out.println(bookings.getListOfBooking().get(0).getStartDateTime());
        out.println(bookings.getListOfBooking().size());
        %>

1 个答案:

答案 0 :(得分:0)

您没有访问正确的文档图层。执行此操作BasicDBObject bookingObj = (BasicDBObject) bookingsList.get(i);时,当startDateTime位于下一层(嵌入文档)时,您将获得文档的最顶层

你应该这样做:

BasicDBList bookingsList = (BasicDBList) theObj.get("bookings");
    for (int i = 0; i < bookingsList.size(); i++) {
        //this one gets the first document
        BasicDBObject bookingObj = (BasicDBObject) bookingsList.get(i);
        //this one gets 'bookings' embedded document, which is also a list
        List<BasicDBObject> embeddedBookingObjList = (List<BasicDBObject>) bookingObj.get("bookings");
        Date startDateTime = embeddedBookingObjList.get(0).getDate("startDateTime");
        booking.setStartDateTime(startDateTime);
    }

我没有处理List个例外,但我相信你可以看到可能发生的错误。顺便说一句,请尝试使用Document,阅读DBObject部分:http://mongodb.github.io/mongo-java-driver/3.2/bson/documents/