I follow this old post to convert POJO to a JSON object using JSP to show a list of users to the browser. However, there is some conflict between the DBCollection
and the MongoCollection
that working to store user input to the cloud database. If it can be solved, I can use it to do other CRUD while learning how to design my web project.
Having said that, is it someway I can use DAO and Service to do CRUD operation?
Type Exception Report
Message com.mongodb.client.internal.MongoCollectionImpl cannot be cast to com.mongodb.DBCollection
Description The server encountered an unexpected condition that prevented it from fulfilling the request.
Exception
java.lang.ClassCastException: com.mongodb.client.internal.MongoCollectionImpl cannot be cast to com.mongodb.DBCollection
com.smartcard.service.UserService.<init>(UserService.java:26)
com.smartcard.controller.admin.ListUsersServlet.doGet(ListUsersServlet.java:27)
javax.servlet.http.HttpServlet.service(HttpServlet.java:626)
javax.servlet.http.HttpServlet.service(HttpServlet.java:733)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
The Converter
public class UserConverter {
public static DBObject toDBOjbect(User u) {
BasicDBObjectBuilder builder = BasicDBObjectBuilder.start().append("email", u.getEmail())
.append("Full Name", u.getFulleName()).append("password", u.getPassword());
if (u.getId() != null)
builder = builder.append("_id", u.getId());
return builder.get();
}
public static User toUser(DBObject userDoc) {
User u = new User();
u.setEmail((String) userDoc.get("email"));
u.setFulleName((String) userDoc.get("fullname"));
u.setPassword((String) userDoc.get("password"));
ObjectId userId = (ObjectId) userDoc.get("_id");
u.setId(u.toString());
return u;
}
}
The Service class to list all user
public class UserService {
// private UserDAO userDAO;
MongoDatabase mdb = dBUtils.getMongoDB();
private DBCollection col;
public UserService() {
this.col = (DBCollection) mdb.getCollection("User");
}
public List<User> listUser() {
List<User> userList = new ArrayList<User>();
DBCursor cursor = col.find();
while (cursor.hasNext()) {
DBObject doc = cursor.next();
User u = UserConverter.toUser(doc);
userList.add(u);
}
return userList;
}
}
Aucun commentaire:
Enregistrer un commentaire