java web application with spark + freemarker + mongodb


Technologies used.

  •  Maven
  • Spark framework
  • Freemarker template engine
  • Java 1.7
  • MongoDB

First create a project template using maven. This project is the one i am following in the Mongodb for Java developers course conducted by 10gen.

After creating the project, edit the pom.xml as follows.

<project xmlns="" xmlns:xsi=""



 <id>Spark repository</id>


Now create a separate resources folder and add the hello.ftl template file inside it.

<h1>Hello ${name}</h1>

Spark is mini java framework which is run on jetty server.

Now add the following java class.

package tengen;

import java.util.HashMap;
import java.util.Map;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
import com.mongodb.ServerAddress;

import spark.Request;
import spark.Response;
import spark.Route;
import spark.Spark;
import freemarker.template.Configuration;
import freemarker.template.Template;

public class HelloWorldMongoDBfreemarkerStyle {

 * @param args
 * @throws UnknownHostException
 * @throws MongoException
 public static void main(String[] args) throws MongoException, UnknownHostException {
 // TODO Auto-generated method stub

final Configuration configuration = new Configuration();
 configuration.setClassForTemplateLoading(HelloWorldfreemarkerstyle.class, "/");
 Mongo client = new Mongo(new ServerAddress("localhost",27017));

 DB database = client.getDB("foo");
 final DBCollection collection = database.getCollection("foo");
 Spark.get(new Route("/") {

 public Object handle(final Request request, final Response response) {
 StringWriter writer = new StringWriter();
 try {
 // TODO Auto-generated method stub
 Template helloTemplate = configuration.getTemplate("hello.ftl");

 DBObject document = collection.findOne();
 helloTemplate.process(document, writer);

 } catch (Exception e) {
 // TODO: handle exception

 return writer;


Now run the mongodb server. Then run the above java file. Go to localhost:4567 address in your browser. You will see “Hello MongoDB”.


there should be a collection named “foo” and inside that the following document.

{“name”:”MongoDB”} 🙂


3 thoughts on “java web application with spark + freemarker + mongodb

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s