Navigation Bar

Saturday, August 1, 2026

A Springboot-React web application example.

Define a Data Model (Java POJO)

Create a simple Java class representing the data you want to send.

Step 1: Generate the Project Structure

The fastest, standard way to bootstrap a Spring Boot application is using Spring Initializr

  1. Open your web browser and navigate to start.spring.io. 
  2. Configure the following project options:
    • Project: Maven (or Gradle, if you prefer)
    • Language: Java
    • Spring Boot: Choose the latest stable, non-SNAPSHOT version
  3. Fill out the Project Metadata:
    • Group: com.example
    • Artifact: springdemo
    • Name: demo
    • Package name: com.example.springdemo
    • Packaging: Jar
    • Java: Choose your installed version (Java 17 or 21 is highly recommended)
  4. Click the Add Dependencies button on the right and add:
    • Spring Web: Contains everything required to build RESTful APIs.
  5. Click Generate at the bottom to download a .zip file of your project.
Extract the zipped folder to a location on your computer.

            Step 2: Open and Explore the Project
  1. Launch your preferred IDE (IntelliJ IDEA, Eclipse, or VS Code).
  2. Choose Open Project and select the root directory of the extracted folder.
  3. Wait for your IDE to download the required Maven libraries.
Locate the main application class file inside src/main/java/com/example/demo/DemoApplication.java:

Step 3: Create the Package Structure and Data Model

Keep your code clean by organizing it into sub-packages.

  1. Right-click on the com.example.demo folder in your IDE file tree.
  2. Select New > Package and name it model.
  3. Inside this new model package, create a new Java class file named User.java.
  4. Copy and paste the following code to represent the structure of the data your API will return:

Step 4: Create the REST Controller

The controller exposes endpoints that handle incoming network requests from React. [1]

  1. Right-click on the main package com.example.demo again.
  2. Select New > Package and name it controller.
  3. Inside this new controller package, create a new Java class file named UserController.java.
package com.example.demo.model;

public class User {
    private int id;
    private String name;
    private String email;

    // Constructor
    public User(int id, String name, String email) {
        this.id = id;
        this.name = name;
        this.email = email;
    }

    // Getters and Setters (Required for Spring to serialize data into JSON)
    public int getId() { return id; }
    public void setId(int id) { this.id = id; }

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

    public String getEmail() { return email; }
    public void setEmail(String email) { this.email = email; }
}
package com.example.demo.controller;

import com.example.demo.model.User;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/api/users")
// Crucial: Allows your React development server on port 3000 to fetch this data safely
@CrossOrigin(origins = "http://localhost:5173")
public class UserController {

    @GetMapping
    public List<User> getAllUsers() {
        // Simulating mock data for demonstration
        return Arrays.asList(
                new User(1, "Alice Smith", "alice@example.com"),
                new User(2, "Bob Jones", "bob@example.com")
        );
    }
}

Add the code below to build your API route endpoints:
package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {

	public static void main(String[] args)
	{
		SpringApplication.run(DemoApplication.class, args);
	}

}




Step 5: Run and Test Your API

  1. Open DemoApplication.java.
  2. Click the green Play/Run icon next to the main method in your IDE.
  3. Check your IDE's console terminal output at the bottom. You should see a log message confirming the server successfully started: Tomcat started on port 8080 (http).
  4. Open your web browser or an API client like Postman.
  5. Go to the URL: http://localhost:8080/api/users
  6. You will see your raw array data printed cleanly as JSON data formatting:

[

  {"id":1,"name":"Alice Smith","email":"alice@example.com"},

                        {"id":2,"name":"Bob Jones","email":"bob@example.com"}
                    ]

Now for the Front End UI development

Install Node.js

Step-by-Step Installation

  1. Run the Installer: Double-click the node-v24.18.0-x64.msi file on your computer.
  2. Follow the Wizard: Click Next, accept the license agreement, and leave the default installation path unchanged.
  3. Native Tools (Optional): If the installer asks to install "Tools for Native Modules" (Chocolatey), you can leave it unchecked for a basic React setup to speed up installation.
  4. Finish: Click Install, then click Finish once complete.

Verify the installation on the command prompt with

node -v


Download and Install VisualStudio Code for your front end development IDE.
You can download from

Step 1: Create a Fresh React Project

Open your Windows Command Prompt or PowerShell, navigate to the folder where you want to keep your project (e.g., cd Documents), and run these commands:

bash

# 1. Create the project using Vite (the modern, fast industry standard)

npm create vite@latest my-react-app -- --template react

 # 2. Navigate into your new project folder

cd my-react-app

 # 3. Install all default React packages

npm install

Step 2: Add Your UserList Component

  1. Open the my-react-app folder in your code editor (like VS Code).
  2. Inside the project folder, locate the src folder.
  3. Inside the src folder, create a new file named UserList.jsx.
  4. Paste the complete UserList.jsx React code we wrote earlier into this file and save it.
import React, { useState, useEffect } from 'react';

function UserList() {
  // State to hold our user array from Spring Boot
  const [users, setUsers] = useState([]);
  // State to track if the network request is still loading
  const [loading, setLoading] = useState(true);
  // State to catch and display any connection errors
  const [error, setError] = useState(null);

  useEffect(() => {
    // 1. Point to your precise Spring Boot URL endpoint
    fetch('http://localhost:8080/api/users')
      .then((response) => {
        // Check if the server responded with an error status (like 404 or 500)
        if (!response.ok) {
          throw new Error(`HTTP error! Status: ${response.status}`);
        }
        return response.json(); // Transform the raw JSON string into a JS array
      })
      .then((data) => {
        setUsers(data);        // Store the user array in state
        setLoading(false);     // Turn off the loading message
      })
      .catch((error) => {
        console.error('Error fetching users:', error);
        setError('Failed to load users from the server.');
        setLoading(false);
      });
  }, []); // Empty dependency array ensures this runs exactly once when component loads

  // 2. Conditional UI rendering based on the request state
  if (loading) return <p style={styles.message}>Loading user profiles...</p>;
  if (error) return <p style={{ ...styles.message, color: 'red' }}>{error}</p>;

  // 3. Render the fetched data into a clean HTML layout
  return (
    <div style={styles.container}>
      <h2 style={styles.heading}>Active Team Members</h2>
      <ul style={styles.list}>
        {users.map((user) => (
          <li key={user.id} style={styles.listItem}>
            <div>
              <strong style={styles.name}>{user.name}</strong>
              <span style={styles.email}>{user.email}</span>
            </div>
            <span style={styles.idBadge}>ID: {user.id}</span>
          </li>
        ))}
      </ul>
    </div>
  );
}

// Quick inline styling for visual layout
const styles = {
  container: { maxWidth: '500px', margin: '40px auto', padding: '20px', fontFamily: 'Arial, sans-serif' },
  heading: { textAlign: 'center', color: '#333' },
  list: { listStyleType: 'none', padding: 0 },
  listItem: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '15px', margin: '10px 0', border: '1px solid #ddd', borderRadius: '6px', backgroundColor: '#f9f9f9' },
  name: { display: 'block', fontSize: '16px', color: '#222' },
  email: { fontSize: '14px', color: '#666' },
  idBadge: { backgroundColor: '#007bff', color: '#fff', padding: '4px 8px', borderRadius: '4px', fontSize: '12px' },
  message: { textAlign: 'center', fontSize: '18px', marginTop: '50px' }
};

export default UserList;

Step 3: Connect UserList to the Main App File

Open the existing src/App.jsx file in your editor, erase everything inside it, and replace it with this clean code to display your component:

App.jsx
import React from 'react';
import UserList from './UserList'; // Imports your user list logic

function App() {
  return (
    <div>
      <UserList />
    </div>
  );
}

export default App;

Step 4: Run Both Servers Simultaneously

  1. Keep your Spring Boot app running in your IDE on port 8080.
  2. Open your terminal in the React project directory and run your development server:

cmd

npm run dev

you will get output

> my-react-app@0.0.0 dev
> vite

  VITE v8.1.5  ready in 331 ms

  ➜  Local:   http://localhost:5173/Network: use --host to expose
  ➜  press h + enter to show help

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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>4.1.0</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.example</groupId>
	<artifactId>demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name/>
	<description/>
	<url/>
	<licenses>
		<license/>
	</licenses>
	<developers>
		<developer/>
	</developers>
	<scm>
		<connection/>
		<developerConnection/>
		<tag/>
		<url/>
	</scm>
	<properties>
		<java.version>17</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-webmvc</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-webmvc-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

Open your browser to 
http://localhost:5173 (or the custom port your React terminal displays). 
You will instantly see Alice Smith and Bob Jones pulled live from your Java application! 






God's Word for the day

The Temptations of Commerce
A merchant can hardly keep from wrongdoing,
  nor is a tradesman innocent of sin.
Many have committed sin for gain,
  and those who seek to get rich will avert their eyes
As a stake is driven firmly into a fissure between stones,
  so sin is wedged in between selling and buying.
If a person is not steadfast in the fear of the Lord,
  His house will be quickly overthrown.
Sirach 27:1 - 3


Gospel teachings of Jesus

Jesus Blesses little children
Then little children were being brought to Him,
  In order that he might lay His hands on them and pray.
The disciples spoke sternly to those who brough them;
  but Jesus said, "Let the children come to me, and do
not stop them; for it is to such as these that the kingdom
  of heaven belongs." And he laid his hands on them and
went on his way.
Mathew 18:13 - 15

No comments:

Post a Comment