如何解决MongoDB连接可以类似于Java servlet中的SQL连接吗?
我在下面的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");
}
解决方法
最后,我发现在声明连接外部服务器的conntionStringPostfix
中缺少@。但是,我仍然无法连接到云数据库。
尝试使其成为配置文件,项目一开始就运行,这将解决您的问题吗?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。