Full Stack Web Application with React and Spring Boot

Full stack web application with React and Spring Boot

Overview

In this blog post, we’re going to develop a simple full stack web application using react and spring boot. Our goal is to display a list of employee data on a React frontend, fetching that data from a Spring Boot backend. We’ll use the exact code you’ve provided, breaking down each part so you can understand how everything fits together.

Full stack web application with react and spring boot

React and Spring Boot

Before we jump into the code, let’s briefly understand why React and Spring Boot are such a popular choice:

  • React (Frontend): A JavaScript library for building user interfaces. It’s declarative, efficient, and makes creating interactive UIs a breeze. Think of it as the “face” of your application.
  • Spring Boot (Backend): A framework that simplifies the development of production-ready, stand-alone Spring applications. It’s robust, secure, and handles all the heavy lifting of data management, business logic, and API creation. This is the “brain” and “data center” of your application.
  • Together, they form a powerful combination where React handles what the user sees and interacts with, while Spring Boot provides the data and services needed to make it all work.

Our Simple Employee Data Application

For this tutorial, we’ll build an application that fetches and displays a list of employees. Here’s a quick overview of what we’ll be doing:

Spring Boot Backend:

  • Define an Emp (Employee) entity: To represent our data.
  • Create a Controller: To expose an API endpoint (/getEmp) that serves employee data.
  • Service layer (implicitly): To handle the business logic of fetching employees (though for this simple example, it might just pass through to a repository).

React Frontend:

  • Use the axios library: To make an API call to our Spring Boot backend.
  • Display the fetched employee data: In a simple table.

Table of Contents:

  • Set up the Spring Boot application (server)
  • Configure the application.properties file to connect the database.
  • Creating the Entity, Repository, Service and Controller for API
  • Setting Up the React Application
  • Connect Frontend and Backend for calling the Spring Boot api using React

Now let’s create the complete full stack web application using React and Spring Boot.

Step 1: Set up the Spring Boot application (server)

Use Spring Initializer or an IDE like IntelliJ or Eclipse to create a new Spring Boot project. Add the following dependencies:

  • Spring Web: For building web applications and REST APIs.
  • Spring Data JPA: For interacting with the database.
  • MySQL Driver: To connect to your MySQL database.

Step 2 : Configure the application.properties File

1. Open the application.properties file and configure your database settings. Here’s an example configuration:

2. Replace your_database_name, your_username, and your_password with your database details.


# Server configuration
server.port = 8081
          
# Database configuration
spring.datasource.url=jdbc:mysql://localhost:3306/your_database_name
spring.datasource.name=your_database_name
spring.datasource.username=your_username
spring.datasource.password=your_password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
          
# JPA configuration
spring.jpa.hibernate.ddl-auto=update
        

For More Details:

If you want to learn more about configuring the application.properties file, check out this detailed article:

Create REST APIs Using Spring Boot: Step-by-Step Guide

Step 3 : Creating the Entity, Repository, Service and Controller for our API

  • Entity Classes: Representing the database table.
  • Controller: Defining the endpoints of the API.
  • Service: Containing the business logic.
  • Repository: Performing database operations.

Let’s create each of these components step by step.

Entity Class (UserData)

This class represents the structure of our employee data. It’s essentially a blueprint for how an employee record will look in our database (or in this simple case, how we’ll define our data).


package com.demo.entity;

import jakarta.persistence.Entity;
import jakarta.persistence.Id;

@Entity 
public class Emp {

    @Id // This marks 'name' as the primary key
    private String name;
    private int age;
    private int salary;

    // Default constructor (important for JPA)
    public Emp() {
        
    }

    // Parameterized constructor
    public Emp(String name, int age, int salary) {
        this.name = name;
        this.age = age;
        this.salary = salary;
    }

    // Getter and Setter methods for all properties
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }

    public int getSalary() {
        return salary;
    }
    public void setSalary(int salary) {
        this.salary = salary;
    }
}

Controller (for defining api endpoint)

This is where we define our API endpoints. The controller acts as the entry point for requests coming from our frontend.


@RestController // This annotation combines @Controller and @ResponseBody
public class EmpController {

    @Autowired // Spring will inject an instance of EmpService here
    private EmpService empService;

    @GetMapping("/getEmp") // This maps HTTP GET requests to "/getEmp"
    public List<Emp> getEmp() {
        // This method calls the service to get employee data
        return empService.getEmp();
    }
}

Service

In this EmpService will perform our database operations why calling repository method


@Service
public class EmpService {

    @Autowired
    private EmpRepo empRepo;

    public List<Emp> getEmp() {
        return empRepo.findAll();
    }
}

Repository

When we following MVC (Model View Controller) this is part that actually perform the database operations for particular table


@Repository
public interface EmpRepo  extends JpaRepository<Emp, String> {
    // JpaRepository provides built-in methods for CRUD operations
    // You can define custom query methods here if needed
}

Run the Application

Run your Spring Boot application. It will automatically create the table in your database based on the Emp entity. and some insert some dummy data in the table like in following image have added

automatic table created

Step 4: Setting Up the React Application

The first step to creating a React application using the command npx create-react-app with you application name like following

npx create-react-app ReactDemo 

After installation, the React application is run using the command npm start and test you application

npx start 

Step 5: Creating the table in react for showing the employees data

You can do the app.js file or create another js file for this Now, Our React application will make a request to the Spring Boot backend and display the data it receives.


import './App.css';
import axios from "axios"; // Import axios for making HTTP requests
import { useEffect, useState } from 'react'; // Import React hooks

function App() {

  // State variable to store the list of employees
  const [employees, setEmployees] = useState([]);

  // useEffect hook runs after the component mounts
  useEffect(() => {
    fetchEmployees(); // Call fetchEmployees when the component first loads
  }, []); // The empty dependency array ensures this runs only once

  // Function to fetch employee data from the backend
  const fetchEmployees = async () => {
    try {
      // Make a GET request to our Spring Boot backend
      const response = await axios.get("http://localhost:8082/getEmp");
      console.log(response.data); // Log the data to the console for debugging
      setEmployees(response.data); // Update the state with the fetched data
    } catch (error) {
      console.error("Error fetching employees:", error);
      // Handle errors gracefully, e.g., display an error message to the user
    }
  }

  return (
    <div className="App">
      <h1>Employee List</h1> {/* Changed from "hello" to something more descriptive */}

      <table>
        <thead>
          <tr>
            <th>Name</th>
            <th>Age</th>
            <th>Salary</th>
          </tr>
        </thead>
        <tbody>
          {employees.map((employee) => ( // Loop through the employees array
            <tr key={employee.name}> {/* Add a unique key for list items */}
              <td>{employee.name}</td>
              <td>{employee.age}</td>
              <td>{employee.salary}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

export default App;

API Calling from React to Spring Boot

The React application is configured to make API calls to the Spring Boot server or application using Axios for HTTP requests


const fetchEmployees = async () => {
  try {
    // Make a GET request to our Spring Boot backend
    const response = await axios.get("http://localhost:8082/getEmp");
    console.log(response.data); // Log the data to the console for debugging
    setEmployees(response.data); // Update the state with the fetched data
  } catch (error) {
    console.error("Error fetching employees:", error);
    // Handle errors gracefully, e.g., display an error message to the user
  }
};

Run your React Application

Run your React application. Once it’s running, you will see all the dummy data from the table displayed on your webpage.

How it All Connects: The Flow

  1. Start Spring Boot: You run your Spring Boot application (e.g., from your IDE or using mvn spring-boot:run). It starts on http://localhost:8082 (or whatever port you configure).
  2. Spring Boot Data: The EmpService (and underlying data access layer) makes dummy employee data available (or fetches it from a database).
  3. Spring Boot API Ready: The EmpController is now listening for requests at /getEmp.
  4. Start React App: You run your React application (e.g., npm start). It starts on http://localhost:3000.
  5. React Component Mounts: When your App component loads in the browser, the useEffect hook triggers WorkspaceEmployees().
  6. React Makes API Call: axios.get("http://localhost:8082/getEmp") sends an HTTP GET request from your browser to your running Spring Boot backend.
  7. Spring Boot Responds: The EmpController receives the request, calls empService.getEmp(), and returns the list of employees as JSON.
  8. React Receives Data: axios gets the JSON response, and response.data contains the employee list.
  9. React Updates UI: setEmployees(response.data) updates the component’s state. React re-renders the App component, and the employees.map() function populates the table with the fetched data.

Next Steps and Improvements

This is just the beginning! Here are some ideas to take your application further:

  • Add Employee: Implement a form in React to add new employees, sending a POST request to your Spring Boot backend.
  • Update/Delete Employee: Add functionality to modify or remove existing employee records.
  • Database Integration: Replace the hardcoded EmpService data with actual database persistence (e.g., using H2, MySQL, PostgreSQL, along with Spring Data JPA repositories).
  • Styling: Make your React UI more visually appealing using CSS frameworks like Bootstrap or Tailwind CSS.
  • Routing: If your application grows, add routing to your React app using react-router-dom to navigate between different pages.
  • Error Handling: Implement more robust error handling on both the frontend and backend to improve reliability.

Conclusion

Congratulations! You’ve just built a basic full-stack web application using React and Spring Boot. You’ve seen how these two powerful technologies work hand-in-hand to create dynamic and data-driven web experiences. This foundation opens up a world of possibilities for building more complex and feature-rich applications.

Youtube Video –

Github Repository –

https://github.com/amangupta7024/React-SpringBoot

Explore our more articles

Leave a Comment