这可能比它需要的要复杂一些,但我正在使用:
- MongoDB数据库
- 火花
- 自由标记
- 爪哇
我无法弄清楚如何访问 mongodb 中的嵌入数据以在网站上打印。我希望能够查看记录,找到哪个接口有一个值为“MGMT”的“标签”,然后打印该接口的信息。问题是,我将它们嵌入到“网络”集合中。我如何访问该信息?
重要的代码行:
爪哇:
try {
Template helloTemplate = configuration.getTemplate("hello.ftl");
DBObject document = collection.findOne();
helloTemplate.process(document, writer);
System.out.println(writer);
} catch (Exception e) {
halt(500);
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
完整代码:
.java:
import com.mongodb.*;
import freemarker.template.Configuration;
import freemarker.template.Template;
import spark.Request;
import spark.Response;
import spark.Route;
import spark.Spark;
import java.io.StringWriter;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;
/**
* Created with IntelliJ IDEA.
* User: sysrjt1
* Date: 6/13/13
* Time: 1:09 PM
* To change this template use File | Settings | File Templates.
*/
public class HelloWorldMongoDBSparkFreemarkerSyle {
public static void main(String[] args) {
final Configuration configuration = new Configuration();
configuration.setClassForTemplateLoading(HelloWorldMongoDBSparkFreemarkerSyle.class, "/");
MongoClient client = null;
try {
client = new MongoClient(new ServerAddress("localhost", 27017 ));
} catch (UnknownHostException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
DB database = client.getDB("systems");
final DBCollection collection;
collection = database.getCollection("systems");
Spark.get(new Route("/") {
@Override
public Object handle(Request request, Response response) {
StringWriter writer = new StringWriter();
try {
Template helloTemplate = configuration.getTemplate("hello.ftl");
DBObject document = collection.findOne();
helloTemplate.process(document, writer);
System.out.println(writer);
} catch (Exception e) {
halt(500);
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
return writer;
}
});
}
}
我的 HTML 模板(hello.ftl):
<!DOCTYPE html>
<html>
<head>
<title>Welcome!</title>
</head>
<body>
<table>
<thead>
<tr>
<th>Name</th>
<th>Management IP</th>
<th>RAM</th>
</tr>
</thead>
<tbody>
<tr>
<td>${name}</td>
<td>${ipAddr}</td> <! -- this line fails -->
<td>${ram}</td>
</tr>
</tbody>
</table>
<h1>Server Name: ${name}</h1>
</body>
</html>
来自 MongoDB:
> db.systems.findOne() { "_id" : ObjectId("51b9dde5d05f675ad37ac990"), "name" : "abcdev01", "networking" : { "interface1" : { "name" : "eth0", "ipAddr" : "12.34.45.56", "sNet" : "255.255.255.0", "label" : "MGMT" }, "interface2" : { "name" : "eth1", "ipAddr" : "1.2.3.4" } }, "ram" : 102390 }