如何在JSP中使用MONGODB

时间:2012-07-03 10:58:17

标签: jsp mongodb

我无法在JSP文件中创建Mongo变量:

<%@ 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>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
    <%
        out.println(request.getParameter("user"));
        Mongo mongo = new Mongo();
    %>
</body>
</html>

它抛出:Mongo无法解析为某种类型。你能帮帮我吗?

3 个答案:

答案 0 :(得分:2)

    <%@ page language="java" 
    contentType="text/html; 
    charset=windows-1256"
     pageEncoding="windows-1256" 
     import="com.mongodb.BasicDBObject"
     import="com.mongodb.DB"
     import="com.mongodb.DBCollection"
     import="com.mongodb.DBCursor"
     import="com.mongodb.MongoClient"
     import="java.net.UnknownHostException"
      %> 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> 
     <head>
     <meta http-equiv="Content-Type" content="text/html; charset=windows-1256"> 
     <title> Test Page</title>
     </head> 
     <body> 



   <% MongoClient mongoClient = null;
try {
    mongoClient = new MongoClient();
} catch (UnknownHostException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
}
// or, to connect to a replica set, supply a seed list of members
//MongoClient mongoClient = new MongoClient(Arrays.asList(new ServerAddress("localhost", 27017),
  //                                    new ServerAddress("localhost", 27018),
    //                                  new ServerAddress("localhost", 27019)));

DB db = mongoClient.getDB("testdoc");
DBCollection coll;
coll = db.getCollection("testdoc");
BasicDBObject doc = new BasicDBObject("Number1", 1).
        append("Number2", 2).append("Number3", 3);

//System.out.println("Data Display");
coll.insert(doc);
DBCursor cursor = coll.find();
try {
   while(cursor.hasNext()) {
       System.out.println(cursor.next());
   }
} finally {
   //mongoClient.dropDatabase("test");
   cursor.close();

}
    %>
     </body>
     </html>

答案 1 :(得分:1)

您是否在类路径中使用了以下jar?

MongoDB 1.8.1
MongoDB-Java-Driver 2.5.2

参考http://www.mkyong.com/mongodb/java-mongodb-hello-world-example/

答案 2 :(得分:1)

尝试将导入添加到页面顶部:

<%@ page import="com.mongodb.Mongo" %>