Accueil > MongoDB > Mongo JEE [step2]

Mongo JEE [step2]


In [step1] we have seen how to execute mongo operations (find, insert, remove) with Java code by using Mongo Java Driver and the Pojo Mapper MongoJack. In this article we will create a WebApp application composed with a Servlet which connects to the Mongo DB and returns the JSON stream array of the logs collection in the HTTP response, on other words when the following URL will be called :

http://localhost:8081/mongo/servlet/logs/ the servlet will return the JSON stream array :

[ 
{ "_id" : { "$oid" : "518d01813bfe01bef797d031"} , 
  "url" : "http://www.mongodb.org/" , 
  "created" : { "$date" : "2013-05-10T14:17:37.515Z"}} , 
{ "_id" : { "$oid" : "518d01813bfe01bef797d032"} , 
  "url" : "http://www.mongodb.org/" , 
  "created" : { "$date" : "2013-05-10T14:17:37.515Z"}} ,
...]

To do that, we will :

Download

You can download step2.zip which hosts the Eclipse Project which contains the explained sources in this article. To use it, unzip it and import this project in your Eclipse workspace. As soon as you will do that, your workspace will look like this :

  • org.samples.mongodb.servlet.LogsServlet is the logs servlet which returns the JSON array.
  • web.xml declares the logs servlet.
  • org.samples.mongodb.server.StartServer starts the embedding Jetty which hosts the WebApp.

Download JARs with maven

In this article we use the Mongo Java Driver. To do that I use this maven dependency :

<dependency>
	<groupId>org.mongodb</groupId>
	<artifactId>mongo-java-driver</artifactId>
	<version>2.11.1</version>
</dependency>

and the Embedded Jetty as server. To do that I use this maven dependency :

<dependency>
	<groupId>org.eclipse.jetty</groupId>
	<artifactId>jetty-webapp</artifactId>
	<version>8.1.10.v20130312</version>
	<scope>test</scope>
</dependency>

The project contains the JARs in the lib, but if you wish to download it with maven , see Download JARs with maven [step1].

WebApp

LogsServlet

Create the org.samples.mongodb.servlet.LogsServlet servlet like this:

package org.samples.mongodb.servlet;

import java.io.IOException;
import java.io.Writer;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.util.JSON;

public class LogsServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		// Connect to Mongo DB
		MongoClientURI mongoURI = new MongoClientURI(
				"mongodb://localhost:27017");
		MongoClient mongo = new MongoClient(mongoURI);
		try {

			// Get "logs" collection from the "websites" DB.
			DB db = mongo.getDB("websites");
			DBCollection coll = db.getCollection("logs");

			// Find all DB object from the DB collection
			DBCursor cursor = coll.find();

			// HTTP response is JSON
			response.setCharacterEncoding("UTF-8");
			response.setContentType("application/json");

			// Write in the HTTP response, the JSON array of the cursor.
			Writer writer = response.getWriter();
			StringBuilder buf = new StringBuilder();
			JSON.serialize(cursor, buf);
			writer.write(buf.toString());
			writer.flush();

		} finally {
			mongo.close();
		}
	}
}

web.xml

Declare the servlet in the src/main/webapp/WEB-INF/web.xml like this :

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	id="WebApp_ID" version="2.5">
	<display-name>Mongo JEE</display-name>

	<servlet>
		<servlet-name>LogsServlet</servlet-name>
		<servlet-class>org.samples.mongodb.servlet.LogsServlet
		</servlet-class>
	</servlet>

	<servlet-mapping>
		<servlet-name>LogsServlet</servlet-name>
		<url-pattern>/servlet/logs/*</url-pattern>
	</servlet-mapping>

</web-app>

Server

StartServer

Create the Java main org.samples.mongodb.server.StartServer which starts the embedding Jetty which hosts the WebApp :

package org.samples.mongodb.server;

import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.ContextHandlerCollection;
import org.eclipse.jetty.server.handler.DefaultHandler;
import org.eclipse.jetty.server.handler.HandlerCollection;
import org.eclipse.jetty.webapp.WebAppContext;

public class StartServer {

	public static void main(String[] args) throws Exception {
		Server server = new Server(8081);

		WebAppContext webappcontext = new WebAppContext("src/main/webapp",
				"/mongo");

		ContextHandlerCollection servlet_contexts = new ContextHandlerCollection();
		webappcontext.setClassLoader(Thread.currentThread()
				.getContextClassLoader());
		HandlerCollection handlers = new HandlerCollection();
		handlers.setHandlers(new Handler[] { servlet_contexts, webappcontext,
				new DefaultHandler() });
		server.setHandler(handlers);

		server.start();
		server.join();
	}
}

This Java main starts an embedding Jetty on the 8081 port and configures a WebApp where sources are hosted in the src/main/webapp folder (where web.xml is hosted).

Test LogsServlet

LogsServlet – Mongo pool

According the Getting Started with Java Driver article :

Note The MongoClient instance actually represents a pool of connections to the database; you will only need one instance of class MongoClient even with multiple threads. See the concurrency doc page for more information.

In our current code of LogsServlet we create a MongoClient instance and close it for each HTTP request. We can improve that by creating a MongoClient and close it just one time (not for each HTTP request). Modify the LogsServlet like this :

package org.samples.mongodb.servlet;

import java.io.IOException;
import java.io.Writer;
import java.net.UnknownHostException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.util.JSON;

public class LogsServlet extends HttpServlet {

	private MongoClient mongo = null;

	@Override
	public void init() throws ServletException {
		super.init();

		// Connect to Mongo DB
		MongoClientURI mongoURI = new MongoClientURI(
				"mongodb://localhost:27017");
		try {
			mongo = new MongoClient(mongoURI);
		} catch (UnknownHostException e) {
			throw new ServletException(e);
		}
	}

	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		// Get "logs" collection from the "websites" DB.
		DB db = mongo.getDB("websites");
		DBCollection coll = db.getCollection("logs");

		// Find all DB object from the DB collection
		DBCursor cursor = coll.find();

		// HTTP response is JSON
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json");

		// Write in the HTTP response, the JSON array of the cursor.
		Writer writer = response.getWriter();
		StringBuilder buf = new StringBuilder();
		JSON.serialize(cursor, buf);
		writer.write(buf.toString());
		writer.flush();

	}

	@Override
	public void destroy() {
		super.destroy();
		if (mongo != null) {
			mongo.close();
		}
	}

}

Conclusion

In this article we have seen how to use Mongo in a JEE Servlet. In the next article [step3] we will see how to we can improve this LogsServlet with Mongo JEE.

Catégories :MongoDB
  1. Aucun commentaire pour l’instant.
  1. Mai 11, 2013 à 11:17
  2. Mai 14, 2013 à 12:47

Laisser un commentaire