Spring MVC CRUD using MongoDB Tutorial
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.
Table Of Contents
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?
- Spring is an open-source framework created to address the complexity of an enterprise application development
- One of the chief advantages of the Spring framework is its layered architecture, which allows a developer to be selective about which of its components they can use while providing a cohesive framework for
J2EE
application development - Spring framework provides support and integration to various technologies for e.g.:
- Support for Transaction Management
- Support for interaction with the different databases
- Integration with the Object Relationship frameworks for e.g. Hibernate, iBatis etc
- Support for Dependency Injection which means all the required dependencies will be resolved with the help of containers
- Support for
REST
style web-services
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:
- Model (M): Model’s responsibility is to manage the application’s data, business logic, and the business rules. It is a
POJO
class which encapsulates the application data given by the controller - View (V): A view is an output representation of the information, such as displaying information or reports to the user either as a text-form or as charts. Views are usually the
JSP
templates written with Java Standard Tag Library (JSTL
) - Controller (C): Controller’s responsibility is to invoke the Models to perform the business logic and then update the view based on the model’s output. In spring framework, the controller part is played by the Dispatcher Servlet
1.2 What is MongoDB?
- MongoDB is a high-performance NoSQL database where each database has collections which in turn has documents. Each document has a different number of fields, size, content, and is stored in a JSON-like format (i.e. Binary JSON (BSN)
- The documents in MongoDB doesn’t need to have a schema defined beforehand. Instead, the fields (i.e. records) can be created on the go
- Data model available within the MongoDB allows developers to represent the hierarchical relationships, store arrays, and other more complex structures easily
- This NoSQL solution often comes with embedding, auto-sharding, and onboard replication for better scalability and high availability
1.2.1 Why MongoDB?
- As a NoSQL type database, MongoDB stores the data in the form of a document. Thus, MongoDB offers more flexibility
- This database supports search by field-name, range queries, and the regular expressions. It often provides queries to return the particular fields inside the documents
- MongoDB offers indexes to improve the search performance within the NoSQL database
- To offer horizontal scalability, MongoDB uses sharding by splitting the data across the many MongoDB occurrences
- Replication: MongoDB can give high availability with the replica sets
Now, open up the Eclipse Ide and let’s start building the application!
2. Spring MVC CRUD using MongoDB Tutorial
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!
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
.
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.
Select the Maven Web App Archetype from the list of options and click next.
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
.
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
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>SpringMvcMongo</groupId> <artifactId>SpringMvcMongo</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> </project>
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.
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
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>SpringMvcMongo</groupId> <artifactId>SpringMvcMongo</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>SpringMvcMongo Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <!-- spring dependency --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.0.5.RELEASE</version> </dependency> <!-- jstl dependency --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- javax servlet api --> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>3.0-alpha-1</version> </dependency> <!-- spring & mongodb --> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-mongodb</artifactId> <version>2.0.6.RELEASE</version> </dependency> <!-- mongodb --> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>3.5.0</version> </dependency> <!-- log4j --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> </dependencies> <build> <finalName>${project.artifactId}</finalName> </build> </project>
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.:
getAll()
: Retrieves the complete user’s list from the databaseadd()
: Adding a new user to the databaseedit()
: Updating the details of an existing user in the databasedelete()
: Deleting a user from the databasefindUserId()
: For fetching a single user from the databasegetDBObject()
: For fetching a single Mongo object from the database
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
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <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> </beans>
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
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.5" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <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> </web-app>
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" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Welcome</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <link rel="stylesheet" href="https://examples.javacodegeeks.com/wp-content/litespeed/localres/aHR0cHM6Ly9tYXhjZG4uYm9vdHN0cmFwY2RuLmNvbS8=bootstrap/4.0.0/css/bootstrap.min.css"> </head> <body> <div class="container"> <h2 id="article_header" class="text-warning" align="center">Spring Mvc and MongoDb Example</h2> <div> </div> <!-- Div to add a new user to the mongo database --> <div id="add_new_user"> <c:url var="addUrl" value="/user/add" /><a id="add" href="${addUrl}" class="btn btn-success">Add user</a> </div> <div> </div> <!-- 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> </html>
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" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>User form</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <link rel="stylesheet" href="https://examples.javacodegeeks.com/wp-content/litespeed/localres/aHR0cHM6Ly9tYXhjZG4uYm9vdHN0cmFwY2RuLmNvbS8=bootstrap/4.0.0/css/bootstrap.min.css"> </head> <body> <div class="container"> <h3 id="form_header" class="text-warning" align="center">User Form</h3> <div> </div> <!-- 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> </html>
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
.
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!
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.
Similarly, developers can perform the ‘Delete’ and ‘Update’ operation on the user records and the resultant output can be seen in Fig. 11.
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.
You can download the full source code of this example here: SpringMvcMongo
your code is not running
I just downloaded the project and it is working fine! :) Maybe you are missing something. Let’s catch up via the support section and debug the issue further! :)
Hi,
Maybe the project need some updates:
1) Uses tomcat-jaspe to process jsp pages
2) implements the WebMvcConfigurer to InternalResourceViewResolver
The spring-servlet did not working for me, maybe deprecated in spring boot.
All the best,
Hi,
This code won’t workout because you are providing servlet name as “SpringController” and filename as “spring”-servlet.xml.. either change filename to SpringController-servlet.xml or serlet name to spring, then it may work.
Thanks.