如何在Java Web项目的context.xml中创建Mongo数据库连接?

huangapple go评论74阅读模式
英文:

How to create the Mongo database connection in context.xml in Java web project?

问题

虽然有很多适当的教程来展示如何在Java中连接关系型数据库,但我对MongoDB与Java一起工作的机制感到怀疑。通常人们会在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.

答案1

得分: 2

(i) JNDI configuration to access MongoDB database (META-INF/context.xml):

<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 (include this within the "web-app" tags):

<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 class:

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>
        ...
英文:

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

(i) JNDI configuration to access MongoDB database (META-INF/context.xml):

&lt;Context&gt;
    &lt;Resource name=&quot;mongodb/mongoClient&quot;
              auth=&quot;Container&quot;
              type=&quot;com.mongodb.MongoClient&quot;
              closeMethod=&quot;close&quot;
              factory=&quot;com.mongodb.client.jndi.MongoClientFactory&quot;
              singleton=&quot;true&quot;
              connectionString=&quot;mongodb://localhost:27017&quot; /&gt;
&lt;/Context&gt;

(ii) WEB-INF/web.xml (include this within the "web-app" tags):

 &lt;resource-ref&gt;
     &lt;res-ref-name&gt;mongodb/mongoClient&lt;/res-ref-name&gt;
     &lt;res-type&gt;com.mongodb.MongoClient&lt;/res-type&gt;
     &lt;res-auth&gt;Container&lt;/res-auth&gt;
&lt;/resource-ref&gt;

(iii) Servlet class:

public class TestServlet extends HttpServlet {

    @Resource(name=&quot;java:comp/env/mongodb/mongoClient&quot;)
    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(&quot;java:comp/env/mongodb/mongoClient&quot;);
        //}
        //catch (NamingException ex) {
        //	throw new ServletException(ex);
        //}

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

(iv) view.jsp:

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

huangapple
  • 本文由 发表于 2020年9月23日 15:38:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/64023181.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定