【发布时间】:2020-12-29 12:39:17
【问题描述】:
我已经创建了以下 MongoDB 连接方法和 mLab 并想做类似使用 MySQL 连接数据库的方式,但我不知道下一步该怎么做。我在网上搜索了许多关于 MVC 文件夹结构的文章,但提供如何连接外部数据库的资源有限。
public class MongoDBTest {
private MongoClientURI mongoURI;
private MongoClient mongoClient;
private String authorization;
private List<Document> users = new ArrayList();
private String owner = "owner";
private String password = "password";
private String connectionStringPostfix = "ds011288.mlab.com:11288/heroku_xxx";
protected MongoCredential credential;
protected MongoDatabase database; //MongoDB super-class initializes and shares the MongoDatabase
//Specify the connection
public MongoDatabase getMongoDB() {
MongoClientURI uri = new MongoClientURI("mongodb://" + this.owner + ":" + this.password + connectionStringPostfix);
MongoDatabase db;
try (MongoClient client = new MongoClient(uri)) {
db = client.getDatabase(uri.getDatabase());
}
return db;
}
public MongoDBTest(String owner, String password) throws UnknownHostException {
this.owner = owner;
this.password = password;
}
// addUser method below
我找到的最接近的资源是this 站点。我应该在 web.xml 上声明它
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<display-name>MongoDB Tutorial</display-name>
<context-param>
<param-name>MONGODB_HOST</param-name>
<param-value>localhost</param-value>
</context-param>
<context-param>
<param-name>MONGODB_PORT</param-name>
<param-value>27017</param-value>
</context-param>
<welcome-file-list>
<welcome-file>productlist.jsp</welcome-file>
</welcome-file-list>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>
我尝试使用类似的方式在 DAO 中连接 mLab,如下所示,但失败了。
public UserDao(MongoClient mc) {
MongoClientURI uri = new MongoClientURI("mongodb://" + this.owner + ":" + this.password + connectionStringPostfix);
this.col = mc.getDatabase(uri.getDatabase()).getCollection("User");
}
【问题讨论】:
标签: java mysql mongodb jsp servlets