MongoDB Integration with Tomcat 8 and JNDI in Spring Boot

In this blog post, we'll explore how to configure MongoDB to connect via JNDI (Java Naming and Directory Interface) in a Spring Boot application and deploy it on Tomcat 8. We will use MongoDB driver version 4.6.1 and Maven 3.9 for dependency management. By the end of this guide, you'll have a working Spring Boot application connected to MongoDB via JNDI and deployed on Tomcat.

Integrating MongoDB with Tomcat 8 via JNDI in a Spring Boot Application

Prerequisites

Before we start, make sure you have the following installed:

  1. Java JDK 8 or later

  2. Apache Tomcat 8

  3. MongoDB

  4. Maven 3.9

  5. An IDE like IntelliJ IDEA or Eclipse

Step 1: Create a New Spring Boot Project

First, we need to create a new Spring Boot project. You can use Spring Initializr to generate the project. Select the following dependencies:

  • Spring Web

  • Spring Data MongoDB

Download the project and import it into your IDE.

Step 2: Configure the pom.xml File

In your pom.xml, add the necessary dependencies for Spring Boot and the MongoDB driver:

<parent>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-parent</artifactId>

<version>2.7.18</version>

<relativePath />

</parent>


<dependencies>

    <dependency>

        <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-starter-data-mongodb</artifactId>

    </dependency>

    <dependency>

        <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-starter-web</artifactId>

    </dependency>

<dependency>

    <groupId>org.mongodb</groupId>

    <artifactId>bson</artifactId>

    <scope>provided</scope>

</dependency>

<dependency>

    <groupId>org.mongodb</groupId>

    <artifactId>bson-record-codec</artifactId>

    <scope>provided</scope>

</dependency>

<dependency>

    <groupId>org.mongodb</groupId>

    <artifactId>mongodb-driver-core</artifactId>

    <scope>provided</scope>

</dependency>

<dependency>

    <groupId>org.mongodb</groupId>

    <artifactId>mongodb-driver-sync</artifactId>

    <scope>provided</scope>     

</dependency>

</dependencies>


Step 3: Configure MongoDB JNDI Resource in Tomcat

Edit the conf/context.xml file in your Tomcat installation directory to define a JNDI resource for MongoDB:

<Context>

    <Resource name="mongodb/MongoDataSource"

              auth="Container"

              type="com.mongodb.client.MongoClient"

              factory="com.mongodb.client.MongoClientFactory"

connectTimeout="0" minSize="10"

              uri="mongodb://localhost:27017/your_database" />

</Context>


Step 4: Configure JNDI in Spring Boot

Configure Spring Boot to use the JNDI resource. Create a MongoConfig class:

import javax.naming.NamingException;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.jndi.JndiTemplate;

import com.mongodb.client.MongoClient;


@Configuration

public class MongoDatasourceConfiguration {

@Bean

public MongoClient mongoSource() throws NamingException {

       String jdbc = "java:comp/env/mongodb/MongoDataSource";

        return (MongoClient) new JndiTemplate().lookup(jdbc);

}

}


Step 5: Create a Model and Repository

Model

Create a simple User model to represent the data:

import org.springframework.data.annotation.Id;

import org.springframework.data.mongodb.core.mapping.Document;


@Document(collection = "users")

public class User {

    @Id

    private String id;

    private String name;

    private String email;


    // Getters and Setters

}


Repository

Create a repository interface for the User model:

import org.springframework.data.mongodb.repository.MongoRepository;


public interface UserRepository extends MongoRepository<User, String> {

}


Step 6: Create a Controller

Create a controller to handle HTTP requests:

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController

@RequestMapping("/users")

public class UserController {


    @Autowired

    private UserRepository userRepository;


    @GetMapping

    public List<User> getAllUsers() {

        return userRepository.findAll();

    }


    @PostMapping

    public User createUser(@RequestBody User user) {

        return userRepository.save(user);

    }


    @GetMapping("/{id}")

    public User getUserById(@PathVariable String id) {

        return userRepository.findById(id).orElse(null);

    }


    @DeleteMapping("/{id}")

    public void deleteUser(@PathVariable String id) {

        userRepository.deleteById(id);

    }

}

Step 7: Configure application.properties

add the following configuration to application.properties file:

spring.data.mongodb.database=<mongo db document>

without this line, the application will read and write to mongo test document.

Step 8: Package the Application as a WAR

To deploy the application on Tomcat, we need to package it as a WAR file. Modify the pom.xml to include the Spring Boot Maven plugin and configure it to package the application as a WAR:

<packaging>war</packaging>


<build>

    <plugins>

        <plugin>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-maven-plugin</artifactId>

        </plugin>

    </plugins>

</build>


Step 9: Update Tomcat library

Update Tomcat Lib <Tomcat_Home>/lib with the following jar:

bson-4.6.1.jar

bson-record-codec-4.6.1.jar

mongodb-driver-core-4.6.1.jar

mongodb-driver-sync-4.6.1.jar


Step 10: Deploy the WAR on Tomcat

Generate the WAR file using Maven:

mvn clean package

Copy the generated WAR file from the target directory to the webapps directory of your Tomcat installation. Start Tomcat and access your application at http://localhost:8080/your-app-name.

Step 11: Test Your Application

Verify that your application is running by accessing the defined endpoints. You can use tools like Postman or curl to send HTTP requests to your application.

Conclusion

In this blog post, we walked through setting up a Spring Boot application with MongoDB connected via JNDI in Tomcat 8. This setup is powerful for building scalable and maintainable web applications. For more information, refer to the following resources:

Comments

Popular posts from this blog

Monitoring and Logging with Prometheus: A Practical Guide

Creating a Complete CRUD API with Spring Boot 3: Authentication, Authorization, and Testing

Logging in Spring Boot 3: Best Practices for Configuration and Implementation