In this tutorial, we will learn how to build a simple Full Stack application using Spring boot as backend and React JS (React Hooks) as frontend.
The objective of this tutorial:
- How to use React Hooks in React application
- How to integrate React app with Spring boot application.
- Axios
- Fetch
- Superagent
- React-axios
- Use-http
- React-request
YouTube Video
What we will build?
- springboot-backend - Develop and expose REST APIs
- react-frontend - Consume REST APIs
1. Develop Spring boot application - Backend
1. Create a Spring Boot Application
>> Create Spring Boot Project in Spring Tool Suite [STS]
2. Add maven dependencies
<?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>3.0.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>net.javaguides</groupId>
<artifactId>springboot-backend</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-backend</name>
<description>Spring Boot backend application</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
3. Create JPA Entity - Employee.java
package net.javaguides.springboot.entity;
import lombok.*;
import jakarta.persistence.*;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Entity
@Table(name = "employees")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(name = "first_name", nullable = false)
private String firstName;
@Column(name = "last_name")
private String lastName;
private String email;
}
4. Create Spring Data JPA Repository - EmployeeRepository.java
package net.javaguides.springboot.repository;
import net.javaguides.springboot.entity.Employee;
import org.springframework.data.jpa.repository.JpaRepository;
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
}
5. Spring Controller with REST API - /api/employees
package net.javaguides.springboot.controller;
import net.javaguides.springboot.entity.Employee;
import net.javaguides.springboot.repository.EmployeeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api")
@CrossOrigin("http://localhost:3000/")
public class EmployeeController {
@Autowired
private EmployeeRepository employeeRepository;
@GetMapping("/employees")
public List<Employee> fetchEmployees(){
return employeeRepository.findAll();
}
}
@CrossOrigin(origins = "http://localhost:3000")
6. Run Spring Boot Application and Test Rest API
package net.javaguides.springboot;
import net.javaguides.springboot.entity.Employee;
import net.javaguides.springboot.repository.EmployeeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringbootBackendApplication implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(SpringbootBackendApplication.class, args);
}
@Autowired
private EmployeeRepository employeeRepository;
@Override
public void run(String... args) throws Exception {
Employee employee1 = Employee.builder()
.firstName("Ramesh")
.lastName("Fadatare")
.email("ramesh@gmail.com")
.build();
Employee employee2 = Employee.builder()
.firstName("Tony")
.lastName("Stark")
.email("tony@gmail.com")
.build();
Employee employee3 = Employee.builder()
.firstName("John")
.lastName("Cena")
.email("cena@gmail.com")
.build();
employeeRepository.save(employee1);
employeeRepository.save(employee2);
employeeRepository.save(employee3);
}
}
Hit this "http://localhost:8080/api/employees" link in a browser will popular list of employees as JSON:
[
{
"id":1,
"firstName":"Ramesh",
"lastName":"Fadatare",
"email":"ramesh@gmail.com"
},
{
"id":2,
"firstName":"Tony",
"lastName":"Stark",
"email":"tony@gmail.com"
},
{
"id":3,
"firstName":"John",
"lastName":"Cena",
"email":"cena@gmail.com"
}
]
2. Build React JS Frontend Application
1 - Create a React UI with Create React App
npx create-react-app react-frontend
react-frontend
├── README.md
├── node_modules
├── package.json
├── .gitignore
├── public
│ ├── favicon.ico
│ ├── index.html
│ ├── logo192.png
│ ├── logo512.png
│ ├── manifest.json
│ └── robots.txt
└── src
├── App.css
├── App.js
├── App.test.js
├── index.css
├── index.js
├── logo.svg
└── serviceWorker.js
- public/index.html is the page template;
- src/index.js is the JavaScript entry point.
2 - Adding Bootstrap in React Using NPM
$ npm install bootstrap --save
import 'bootstrap/dist/css/bootstrap.min.css';
src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import 'bootstrap/dist/css/bootstrap.min.css';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();
3. React Service Component - REST API Call
npm add axios
import axios from 'axios';
const EMPLOYEE_API_BASE_URL = 'http://localhost:8080/api/employees';
class EmployeeService{
getEmployees(){
return axios.get(EMPLOYEE_API_BASE_URL);
}
}
export default new EmployeeService();
export default new EmployeeService();
4. Develop a React Component
import React, {useState, useEffect} from 'react'
import EmployeeService from '../services/EmployeeService';
function EmployeeComponent() {
const [employees, setEmployees] = useState([])
useEffect(() => {
getEmployees()
}, [])
const getEmployees = () => {
EmployeeService.getEmployees().then((response) => {
setEmployees(response.data)
console.log(response.data);
});
};
return (
<div className = "container">
<h1 className = "text-center"> Employees List</h1>
<table className = "table table-striped">
<thead>
<tr>
<th> Employee Id</th>
<th> Employee First Name</th>
<th> Employee Last</th>
<th> Employee Email</th>
</tr>
</thead>
<tbody>
{
employees.map(
employee =>
<tr key = {employee.id}>
<td> {employee.id }</td>
<td> {employee.firstName }</td>
<td> {employee.lastName }</td>
<td> {employee.email }</td>
</tr>
)
}
</tbody>
</table>
</div>
)
}
export default EmployeeComponent
useState() hook
The useState is a Hook (function) that allows you to have state variables in functional components. You pass the initial state to this function and it returns a variable with the current state value (not necessarily the initial state) and another function to update this value. const [employees, setEmployees] = useState([])
useEffect() hook
The useEffect Hook allows us to perform side effects (an action) in the function components. It does not use components lifecycle methods that are available in class components. In other words, Effects Hooks are equivalent to componentDidMount(), componentDidUpdate(), and componentWillUnmount() lifecycle methods.Side effects have common features which the most web applications need to perform, such as:
- Updating the DOM,
- Fetching and consuming data from a server API,
- Setting up a subscription, etc.
useEffect(() => {
getEmployees()
}, [])
const getEmployees = () => {
EmployeeService.getEmployees().then((response) => {
setEmployees(response.data)
console.log(response.data);
});
};
5. App.js
import './App.css';
import EmployeeComponent from './components/EmployeeComponent';
function App() {
return (
<EmployeeComponent />
);
}
export default App;
6. Run React App
npm start
yarn start
Comments
Post a Comment
Leave Comment