MongoDB
 sql >> Base de Dados >  >> NoSQL >> MongoDB

Como criar a conexão de banco de dados Mongo em context.xml no projeto web Java?


Exemplo de código servlet/JSP com configuração para conectar-se ao banco de dados MongoDB e visualizar os resultados de uma consulta na página JSP.

(i) Configuração JNDI para acessar o banco de dados MongoDB (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 (inclua isso nas tags "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) Classe 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>
    ...