如何在Java Web项目的context.xml中创建Mongo数据库连接? [英] How to create the Mongo database connection in context.xml in Java web project?

查看:84
本文介绍了如何在Java Web项目的context.xml中创建Mongo数据库连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尽管有许多适当的教程来展示如何在Java中连接关系数据库,但我确实对与Java一起使用的MongoDB机制感到怀疑.通常,人们会在context.xml中创建一个连接,以使用JSP/servlet与关系数据库进行交互以执行Web项目.但是,对于NoSQL数据库,我没有获得任何有关如何以一种很好的构造方式执行此连接的资源,而不是许多最近使用框架且可以无缝工作的资源.

Although there are many proper tutorials to show how to connect relational database in Java, I really in doubt with the MongoDB mechanism working with Java. Normally people would create a connection in context.xml to interact with a relational database with JSP/servlet to do web project. However, with NoSQL database, I don't quite get any resources on how to perform this connection in a nice constructed way rather than many resources with framework lately and working seamlessly.

如果有专家可以告诉我,我真的非常感激它.

If any experts could show me how really highly appreciate it.

推荐答案

对具有配置的servlet/JSP代码进行示例,以连接到MongoDB数据库并在JSP页面中查看查询结果.

Sample servlet/JSP code with configuration to connect to MongoDB database and view a query results in the JSP page.

(i)用于访问MongoDB数据库(META-INF/context.xml)的JNDI配置:

<Context>
    <Resource name="mongodb/mongoClient"
              auth="Container"
              type="com.mongodb.MongoClient"
              closeMethod="close"
              factory="com.mongodb.client.jndi.MongoClientFactory"
              singleton="true"
              connectionString="mongodb://localhost:27017" />
</Context>

(ii)WEB-INF/web.xml(将其包含在"web-app"标签内):

 <resource-ref>
     <res-ref-name>mongodb/mongoClient</res-ref-name>
     <res-type>com.mongodb.MongoClient</res-type>
     <res-auth>Container</res-auth>
</resource-ref>

(iii)Servlet类:

public class TestServlet extends HttpServlet {

    @Resource(name="java:comp/env/mongodb/mongoClient")
    private MongoClient client;

    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        
        // ---- This works too; can be used instead of the @Resource  ----
        //try {
        //  Context ctx = new InitialContext();
        //  client = (MongoClient) ctx.lookup("java:comp/env/mongodb/mongoClient");
        //}
        //catch (NamingException ex) {
        //  throw new ServletException(ex);
        //}

        MongoCollection<Document> coll = client.getDatabase("test")
                                               .getCollection("books");
        
        List<Document> docData = new ArrayList<>();
        coll.find()
             .projection(new Document("title", 1)
                                .append("author", 1)
                                .append("_id", 0))
            .limit(10)
            .into(docData);
        List<String> data = docData.stream()
                                   .map(doc -> doc.get("title") + ", " + doc.get("author"))
                                   .collect(Collectors.toList());
        req.setAttribute("bookdata", data);
    
        RequestDispatcher view = req.getRequestDispatcher("view.jsp");
        view.forward(req, resp);
    }
}

(iv)view.jsp:

<html>
    <head>
        <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
        <title>Test App</title>
    </head>
    <body>
        <h3>Books List</h3>
    
        <c:forEach items="${bookdata}" var="book">
            ${book}<br>
        </c:forEach>
    ...

这篇关于如何在Java Web项目的context.xml中创建Mongo数据库连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆