0

我无法在 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 无法解析为类型。你可以帮帮我吗?

4

3 回答 3

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>
于 2013-05-03T02:56:27.443 回答
1

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

<%@ page import="com.mongodb.Mongo" %>
于 2012-07-03T13:44:34.607 回答
1

您在类路径中使用过以下 jar 吗?

MongoDB 1.8.1
MongoDB-Java-Driver 2.5.2

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

于 2012-07-03T11:02:01.127 回答