Spring MVC CRUD using MongoDB Tutorial (original) (raw)

Hello readers, in this tutorial we will create a simple Spring MVC application that uses a document-oriented NoSQL database for its database layer. For this tutorial, we’ll perform the basic Create, Read, Update, and Delete database operations for managing the list of users.

1. Introduction

If you have installed the MongoDB application (version 3.6.X) on Windows or Ubuntu operating system and you wish to learn this tutorial, then follow the below steps. It is very simple, but before moving further let’s take a look at the spring framework, MongoDB, and their features.

1.1 What is Spring framework?

1.1.1 What is Spring MVC Framework?

Model-View-Controller (MVC) is a well-known design pattern for designing the GUI based applications. It mainly decouples the business logic from UI by separating the roles of Model, View, and Controller in an application. This pattern divides the application into three components to separate the internal representation of the information from the way it is being presented to the user. The three components are:

Fig. 1: Model View Controller (MVC) Overview

Fig. 1: Model View Controller (MVC) Overview

1.2 What is MongoDB?

1.2.1 Why MongoDB?

Now, open up the Eclipse Ide and let’s start building the application!

Below are the steps involved in developing this application.

2.1 Tools Used

We are using Eclipse Kepler SR2, JDK 8 and Maven. Having said that, we have tested the code against JDK 1.7 and it works well.

2.2 Project Structure

Firstly, let’s review the final project structure, in case you are confused about where you should create the corresponding files or folder later!

Fig. 2: Application Project Structure

Fig. 2: Application Project Structure

2.3 Project Creation

This section will demonstrate on how to create a Java-based Maven project with Eclipse. In Eclipse IDE, go to File -> New -> Maven Project.

Fig. 3: Create Maven Project

Fig. 3: Create Maven Project

In the New Maven Project window, it will ask you to select project location. By default, ‘Use default workspace location’ will be selected. Just click on next button to proceed.

Fig. 4: Project Details

Fig. 4: Project Details

Select the Maven Web App Archetype from the list of options and click next.

Fig. 5: Archetype Selection

Fig. 5: Archetype Selection

It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT.

Fig. 6: Archetype Parameters

Fig. 6: Archetype Parameters

Click on Finish and the creation of a maven project is completed. If you observe, it has downloaded the maven dependencies and a pom.xml file will be created. It will have the following code:

pom.xml

4.0.0 SpringMvcMongo SpringMvcMongo 0.0.1-SNAPSHOT war

We can start adding the dependencies that developers want like Spring MVC, Servlet API, MongoDB, and Log4j etc. Let’s start building the application!

3. Application Building

Below are the steps involved in developing this application.

3.1 Database & Table Creation

The following script creates a database called mydb with a collection as mycollection. Open the Mongo terminal and execute the script.

use mydb

db.mycollection.insertMany( [ { "id" : "101", "name" : "Daniel Atlas" }, { "id" : "102", "name" : "Charlotte Neil" }, { "id" : "97", "name" : "tom jackmen" } ] )

db.mycollection.find()

If everything goes well, the database and the collection will be shown in the Mongo Workbench.

Fig. 7: Database and Table Creation

Fig. 7: Database and Table Creation

3.2 Maven Dependencies

In this example, we are using the most stable Spring web-mvc, MongoDB, and Log4j version in order to set-up the Spring MVC and MongoDB functionality. The updated file will have the following code:

pom.xml

4.0.0 SpringMvcMongo SpringMvcMongo war 0.0.1-SNAPSHOT SpringMvcMongo Maven Webapp http://maven.apache.org org.springframework spring-webmvc 5.0.5.RELEASE javax.servlet jstl 1.2 javax.servlet servlet-api 3.0-alpha-1 org.springframework.data spring-data-mongodb 2.0.6.RELEASE org.mongodb mongo-java-driver 3.5.0 log4j log4j 1.2.17 ${project.artifactId}

3.3 Java Class Creation

Let’s create the different Java files required to carry out this tutorial.

3.3.1 Implementation of Factory class

The factory class consists of the getMongo() method to fetch the Mongo database reference using the hostname and the port no. This class also consists of the getDb() and getCollection() methods for fetching the reference database and collection. Add the following code to it:

MongoFactory.java

package com.jcg.springmvc.mongo.factory;

import org.apache.log4j.Logger;

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

@SuppressWarnings("deprecation") public class MongoFactory {

private static Logger log = Logger.getLogger(MongoFactory.class);

private static Mongo mongo;

private MongoFactory() { }

// Returns a mongo instance.
public static Mongo getMongo() {
    int port_no = 27017;
    String hostname = "localhost";		
    if (mongo == null) {
        try {
            mongo = new Mongo(hostname, port_no);																		
        } catch (MongoException ex) {
            log.error(ex);
        }
    }
    return mongo;
}

// Fetches the mongo database.
public static DB getDB(String db_name) {		
    return getMongo().getDB(db_name);
}

// Fetches the collection from the mongo database.
public static DBCollection getCollection(String db_name, String db_collection) {
    return getDB(db_name).getCollection(db_collection);
}

}

3.3.2 Implementation of POJO class

This model class defines the schema as per which the user data will be stored in the Mongo database. Add the following code to it:

User.java

package com.jcg.springmvc.mongo;

import java.io.Serializable;

public class User implements Serializable {

private static final long serialVersionUID = 1L;

private String id, name;

public User() {
    super();
}

public User(String id, String name) {
    super();
    this.id = id;
    this.name = name;
}

public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

}

3.3.3 Implementation of Service class

The UserService.java performs the basic database operations. This service class defines the CRUD operations and has the following methods i.e.:

Add the following code to it:

UserService.java

package com.jcg.springmvc.mongo;

import java.util.ArrayList; import java.util.List; import java.util.Random;

import org.apache.log4j.Logger; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional;

import com.jcg.springmvc.mongo.factory.MongoFactory; import com.mongodb.BasicDBObject; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.DBObject;

@Service("userService") @Transactional public class UserService {

static String db_name = "mydb", db_collection = "mycollection";
private static Logger log = Logger.getLogger(UserService.class);

// Fetch all users from the mongo database.
public List getAll() {
    List user_list = new ArrayList();
    DBCollection coll = MongoFactory.getCollection(db_name, db_collection);

    // Fetching cursor object for iterating on the database records.
    DBCursor cursor = coll.find();	
    while(cursor.hasNext()) {			
        DBObject dbObject = cursor.next();

        User user = new User();
        user.setId(dbObject.get("id").toString());
        user.setName(dbObject.get("name").toString());

        // Adding the user details to the list.
        user_list.add(user);
    }
    log.debug("Total records fetched from the mongo database are= " + user_list.size());
    return user_list;
}

// Add a new user to the mongo database.
public Boolean add(User user) {
    boolean output = false;
    Random ran = new Random();
    log.debug("Adding a new user to the mongo database; Entered user_name is= " + user.getName());
    try {			
        DBCollection coll = MongoFactory.getCollection(db_name, db_collection);

        // Create a new object and add the new user details to this object.
        BasicDBObject doc = new BasicDBObject();
        doc.put("id", String.valueOf(ran.nextInt(100))); 
        doc.put("name", user.getName());			

        // Save a new user to the mongo collection.
        coll.insert(doc);
        output = true;
    } catch (Exception e) {
        output = false;
        log.error("An error occurred while saving a new user to the mongo database", e);			
    }
    return output;
}

// Update the selected user in the mongo database.
public Boolean edit(User user) {
    boolean output = false;
    log.debug("Updating the existing user in the mongo database; Entered user_id is= " + user.getId());
    try {
        // Fetching the user details.
        BasicDBObject existing = (BasicDBObject) getDBObject(user.getId());

        DBCollection coll = MongoFactory.getCollection(db_name, db_collection);

        // Create a new object and assign the updated details.
        BasicDBObject edited = new BasicDBObject();
        edited.put("id", user.getId()); 
        edited.put("name", user.getName());

        // Update the existing user to the mongo database.
        coll.update(existing, edited);
        output = true;
    } catch (Exception e) {
        output = false;
        log.error("An error has occurred while updating an existing user to the mongo database", e);			
    }
    return output;
}

// Delete a user from the mongo database.
public Boolean delete(String id) {
    boolean output = false;
    log.debug("Deleting an existing user from the mongo database; Entered user_id is= " + id);
    try {
        // Fetching the required user from the mongo database.
        BasicDBObject item = (BasicDBObject) getDBObject(id);

        DBCollection coll = MongoFactory.getCollection(db_name, db_collection);

        // Deleting the selected user from the mongo database.
        coll.remove(item);
        output = true;			
    } catch (Exception e) {
        output = false;
        log.error("An error occurred while deleting an existing user from the mongo database", e);			
    }	
    return output;
}

// Fetching a particular record from the mongo database.
private DBObject getDBObject(String id) {
    DBCollection coll = MongoFactory.getCollection(db_name, db_collection);

    // Fetching the record object from the mongo database.
    DBObject where_query = new BasicDBObject();

    // Put the selected user_id to search.
    where_query.put("id", id);
    return coll.findOne(where_query);
}

// Fetching a single user details from the mongo database.
public User findUserId(String id) {
    User u = new User();
    DBCollection coll = MongoFactory.getCollection(db_name, db_collection);

    // Fetching the record object from the mongo database.
    DBObject where_query = new BasicDBObject();
    where_query.put("id", id);

    DBObject dbo = coll.findOne(where_query);		
    u.setId(dbo.get("id").toString());
    u.setName(dbo.get("name").toString());

    // Return user object.
    return u;
}

}

3.3.4 Implementation of Controller class

This is a typical spring controller which is annotated by the Spring MVC annotation types. This class consists of the different request mapping methods which interact with the database to perform the basic operations. Let’s write a quick Java program in the spring controller class to handle the HTTP requests. Add the following code to it.

UserController.java

package com.jcg.springmvc.mongo.controller;

import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam;

import com.jcg.springmvc.mongo.User; import com.jcg.springmvc.mongo.UserService;

@Controller @RequestMapping("/user") public class UserController {

private static Logger log = Logger.getLogger(UserController.class);

@Resource(name="userService")
private UserService userService;

// Displaying the initial users list.
@RequestMapping(value = "/list", method = RequestMethod.GET)
public String getPersons(Model model) {
    log.debug("Request to fetch all users from the mongo database");
    List user_list = userService.getAll();		
    model.addAttribute("users", user_list);		
    return "welcome";
}

// Opening the add new user form page.
@RequestMapping(value = "/add", method = RequestMethod.GET)
public String addUser(Model model) {
    log.debug("Request to open the new user form page");
    model.addAttribute("userAttr", new User());
    return "form";
}

// Opening the edit user form page.
@RequestMapping(value = "/edit", method = RequestMethod.GET)
public String editUser(@RequestParam(value="id", required=true) String id, Model model) {
    log.debug("Request to open the edit user form page");	
    model.addAttribute("userAttr", userService.findUserId(id));		
    return "form";
}

// Deleting the specified user.
@RequestMapping(value = "/delete", method = RequestMethod.GET)
public String delete(@RequestParam(value="id", required=true) String id, Model model) {
    userService.delete(id);
    return "redirect:list";
}

// Adding a new user or updating an existing user.
@RequestMapping(value = "/save", method = RequestMethod.POST)
public String save(@ModelAttribute("userAttr") User user) {
    if(user.getId() != null && !user.getId().trim().equals("")) {
        userService.edit(user);
    } else {
        userService.add(user);
    }
    return "redirect:list";
}

}

3.4 Configuration Files

Let’s write all the configuration files involved in this tutorial.

3.4.1 Spring Configuration File

To configure the spring framework, we need to implement a bean configuration file i.e. spring-servlet.xml which provide an interface between the basic Java class and the outside world. Put this XML file in the SpringMvcMongo/src/main/webapp/WEB-INF folder and add the following code to it:

spring-servlet.xml

<context:component-scan base-package="com.jcg.springmvc.mongo" />
    
<!-- Resolves Views Selected For Rendering by @Controllers to *.jsp Resources in the /WEB-INF/ Folder -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/views/" />
    <property name="suffix" value=".jsp" />
</bean>
              

3.4.2 Web Deployment Descriptor

The web.xml file declares one servlet (i.e. Dispatcher Servlet) to receive all kind of the requests and specifies the default page when accessing the application. Dispatcher servlet here acts as a front controller. Add the following code to it:

web.xml

<display-name>SpringMvcMongo</display-name>

<!-- Spring Configuration - Processes Application Requests -->
<servlet>
    <servlet-name>SpringController</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>SpringController</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

<!-- Welcome File List -->
<welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
</welcome-file-list>

3.5 Creating JSP Views

Spring Mvc supports many types of views for different presentation technologies. These include – JSP, HTML, XML etc. So let us write the simple views in SpringMvcMongo/src/main/webapp/WEB-INF/views folder.

3.5.1 Welcome Page

This page simply fetches the user’s list from the database and displays it on the webpage. Add the following code to it:

welcome.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

Welcome

Spring Mvc and MongoDb Example

 
Add user
 
    	<!-- Table to display the user list from the mongo database -->
    	<table id="users_table" class="table">
        	<thead>
            	<tr align="center">
            		<th>Id</th><th>Name</th><th colspan="2"></th>
            	</tr>
        	</thead>
        	<tbody>
            	<c:forEach items="${users}" var="user">
                	<tr align="center">
                    	<td><c:out value="${user.id}" /></td>
                    	<td><c:out value="${user.name}" /></td>
                    	<td>
                        	<c:url var="editUrl" value="/user/edit?id=${user.id}" /><a id="update" href="${editUrl}" class="btn btn-warning">Update</a>
                    	</td>
                    	<td>
                        	<c:url var="deleteUrl" value="/user/delete?id=${user.id}" /><a id="delete" href="${deleteUrl}" class="btn btn-danger">Delete</a>
                    	</td>
                	</tr>
            	</c:forEach>
        	</tbody>
    	</table>
    </div>	    
</body>

3.5.2 Form Page

This page displays a form page which is used to add a new user or update an existing user in the database. Add the following code to it:

form.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

User form

User Form

 
        <!-- User input form to add a new user or update the existing user-->
        <c:url var="saveUrl" value="/user/save" />
        <form:form id="user_form" modelAttribute="userAttr" method="POST" action="${saveUrl}">
        	<form:hidden path="id" />
            <label for="user_name">Enter Name: </label>
            <form:input id="user_name" cssClass="form-control" path="name" />
            <div> </div>

            <button id="saveBtn" type="submit" class="btn btn-primary">Save</button>
        </form:form>
    </div>
</body>

4. Run the Application

As we are ready for all the changes, let us compile the project and deploy the application on the Tomcat7 server. To deploy the application on Tomat7, right-click on the project and navigate to Run as -> Run on Server.

Fig. 8: How to Deploy Application on Tomcat

Fig. 8: How to Deploy Application on Tomcat

Tomcat will deploy the application in its web-apps folder and shall start its execution to deploy the project so that we can go ahead and test it in the browser.

5. Project Demo

Open your favorite browser and hit the following URL. The output page will be displayed.

http://localhost:8080/SpringMvcMongo/user/list

Server name (localhost) and port (8080) may vary as per your tomcat configuration. Developers can debug the example and see what happens after every step. Enjoy!

Fig. 9: Application Index Page

Fig. 9: Application Index Page

Developers can click the ‘Add user’ button to add a new user to the Mongo collection and the output as shown in Fig. 10 will display the updated user records.

Fig. 10: User list after Adding a new user

Fig. 10: User list after Adding a new user

Similarly, developers can perform the ‘Delete’ and ‘Update’ operation on the user records and the resultant output can be seen in Fig. 11.

Fig. 11: User list after performing a Delete and Update operation

Fig. 11: User list after performing a Delete and Update operation

That’s all for this post. Happy Learning!

6. Conclusion

In this section, developers learned how to create a Spring MVC application using the Mongo database. Developers can download the sample application as an Eclipse project in the Downloads section. Remember to update the database connection settings.

7. Download the Eclipse Project

This was an example of Mongo database with Spring MVC.

Download
You can download the full source code of this example here: SpringMvcMongo