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.
- Open
your web browser and navigate to start.spring.io.
- Configure
the following project options:
- Project:
Maven (or Gradle, if you prefer)
- Language:
Java
- Spring
Boot: Choose the latest stable, non-SNAPSHOT version
- 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)
- Click
the Add Dependencies button on the right and add:
- Spring
Web: Contains everything required to build RESTful APIs.
- Click
Generate at the bottom to download a .zip file of your project.
- Launch
your preferred IDE (IntelliJ IDEA, Eclipse, or VS Code).
- Choose
Open Project and select the root directory of the extracted folder.
- Wait
for your IDE to download the required Maven libraries.
Step 3: Create the Package
Structure and Data Model
Keep your code clean by
organizing it into sub-packages.
- Right-click
on the com.example.demo folder in your IDE file tree.
- Select
New > Package and name it model.
- Inside
this new model package, create a new Java class file named User.java.
- 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]
- Right-click on the main package com.example.demo
again.
- Select New > Package and name it
controller.
- 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") ); } }
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
- Open DemoApplication.java.
- Click the green Play/Run icon next to the
main method in your IDE.
- 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).
- Open your web browser or an API client like
Postman.
- Go to the URL: http://localhost:8080/api/users
- You will see your raw array data printed cleanly as
JSON data formatting:
[
{"id":1,"name":"Alice
Smith","email":"alice@example.com"},
Install Node.js
Step-by-Step Installation
- Run
the Installer: Double-click the node-v24.18.0-x64.msi file on your
computer.
- Follow
the Wizard: Click Next, accept the license agreement, and leave
the default installation path unchanged.
- 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.
- Finish:
Click Install, then click Finish once complete.
Verify the installation on the
command prompt with
node -v
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
cd my-react-app
Step 2: Add Your UserList
Component
- Open
the my-react-app folder in your code editor (like VS Code).
- Inside
the project folder, locate the src folder.
- Inside
the src folder, create a new file named UserList.jsx.
- 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:
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
- Keep
your Spring Boot app running in your IDE on
port 8080.
- 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
<?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>
No comments:
Post a Comment