Hello,
Today we will create a spring boot CRUD application. In, this example, we are using the MySQL database to store data, to view and manage the data we will use react Js library in the frontend part. For API testing we will use Postman.
In this article, We will display data using react application. We will show the list of employees in the table format.
Let’s start. Firstly we will create a GET request method in the controller. So, go to the EmployeeController class and add this method:
@GetMapping("/employees")
public ResponseEntity<List<Employee>> getEmployees(){
return ResponseEntity.ok(employeeService.getEmployees());
}
The final version of the controller class is:
package com.crud.controller;
import com.crud.entity.Employee;
import com.crud.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@CrossOrigin(origins = "http://localhost:3000/")
@RestController
@RequestMapping("/api/v1")
public class EmployeeController {
@Autowired
private EmployeeService employeeService;
@PostMapping("/employees")
public ResponseEntity<?> createEmployee(@RequestBody Employee employee) {
employeeService.save(employee);
return new ResponseEntity<>("Employee Created Successfully",HttpStatus.CREATED);
}
@GetMapping("/employees")
public ResponseEntity<List<Employee>> getEmployees(){
return ResponseEntity.ok(employeeService.getEmployees());
}
}
Then create a new List<Employee>getEmployees() method in the EmployeeSeervice interface. After that implement the method in the EmployeeServiceImpl class. The code should be like this:
Interface:
package com.crud.service;
import com.crud.entity.Employee;
import java.util.List;
public interface EmployeeService {
Employee save(Employee employee); // for save employee
List<Employee> getEmployees(); // get the list of employees
}
Implementation class: add this below code
@Override
public List<Employee> getEmployees() {
return employeeRepository.findAll();
}
The final version of the EmployeeServiceImpl class is:
package com.crud.serviceImpl;
import com.crud.entity.Employee;
import com.crud.repository.EmployeeRepository;
import com.crud.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class EmployeeServiceImpl implements EmployeeService {
@Autowired
private EmployeeRepository employeeRepository;
@Override
public Employee save(Employee employee) {
return employeeRepository.save(employee);
}
@Override
public List<Employee> getEmployees() {
return employeeRepository.findAll();
}
}
Now, come to the frontend part, create a method in the EmployeeService.js file which will call the HTTP GET request using Axios.
Declare the config first:
var getConfig = {
method: 'get',
headers: {}
};
Then create a method for returning the response:
export const get = (url) => {
return axios({ ...getConfig, url: baseUrl + url })
}
The completed file looks like this:
import axios from "axios";
const baseUrl = "http://localhost:8090/api/v1"
var postConfig = {
method: 'post',
headers: {
'Content-Type': 'application/json'
}
}
var getConfig = {
method: 'get',
headers: {}
};
export const save = (url, data) => {
return axios({ ...postConfig, url: baseUrl + url, data: data })
}
export const get = (url) => {
return axios({ ...getConfig, url: baseUrl + url })
}
Then create the Employee.js file in the employee’s folder. and create a state to store the list of employees. Then create another method to get the employees. After that using useEffect() call the method every time when the page is rendered.
const [employees, setEmployees] = useState([]) // created the employee state
// created the method which will get the list of employees
const getEmployees = () => {
get("/employees")
.then(res => {
console.log(res.data)
setEmployees(res.data)
})
.catch(err => console.log(err))
}
Then using map(), iterate the employee’s array and print them in the table body.
{
employees?.map(employee => {
return (
<tr key={employee.id}>
<td>{employee.id}</td>
<td>{employee.firstName}</td>
<td>{employee.lastName}</td>
<td>{employee.email}</td>
<td>{employee.address}</td>
<td>{employee.designation}</td>
<td>{employee.age}</td>
</tr>
)
})
}
The final version of the Employees.js file looks like this:
import React, { useEffect, useState } from 'react'
import { Container, Row, Col, Card, Table } from 'react-bootstrap'
import { get } from '../service/EmployeeService'
const Employees = () => {
const [employees, setEmployees] = useState([])
const getEmployees = () => {
get("/employees")
.then(res => {
console.log(res.data)
setEmployees(res.data)
})
.catch(err => console.log(err))
}
useEffect(() => {
getEmployees() // called the method each time when the page is loaded
}, [])
console.log(employees)
return (
<>
<Container>
<Row>
<Col>
<Card>
<Card.Header>Employee List</Card.Header>
<Card.Body>
<Table striped bordered hover size="sm">
<thead>
<tr>
<th>#</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Address</th>
<th>Designation</th>
<th>Age</th>
</tr>
</thead>
<tbody>
{
employees?.map(employee => {
return (
<tr key={employee.id}>
<td>{employee.id}</td>
<td>{employee.firstName}</td>
<td>{employee.lastName}</td>
<td>{employee.email}</td>
<td>{employee.address}</td>
<td>{employee.designation}</td>
<td>{employee.age}</td>
</tr>
)
})
}
</tbody>
</Table>
</Card.Body>
</Card>
</Col>
</Row>
</Container>
</>
)
}
export default Employees
Now create another route for displaying the list of employees.
Go to the App.js file and add this route. Of course, import the Employees.js file at the top of the file.
<Route path="/employees" element={<Employees />} />
The final version of this file looks like this:
import React from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
import { BrowserRouter as Router, Route, Routes, Link } from "react-router-dom";
import AddEmployees from './components/employees/AddEmployees';
import Home from './components/common/Home';
import Navigation from './components/common/Navigation';
import Employees from './components/employees/Employees';
function App() {
return (
<>
<Navigation />
<Routes>
<Route path="/" element={<Home />} />
<Route path="/add-employee" element={<AddEmployees />} />
<Route path="/employees" element={<Employees />} />
</Routes>
</>
);
}
export default App;
And also create a link in the navigation bar, it looks like this:
<Link to="/employees">Employee List</Link>
The final version of the Navigation.js file looks like this:
import React from 'react'
import { Container, Nav, Navbar, NavDropdown } from 'react-bootstrap'
import { Link } from 'react-router-dom'
import './common.css'
const Navigation = () => {
return (
<Navbar bg="light" expand="lg">
<Container>
<Navbar.Brand href="/">Spring Boot- React JS</Navbar.Brand>
<Navbar.Toggle aria-controls="basic-navbar-nav" />
<Navbar.Collapse id="basic-navbar-nav">
<Nav className="me-auto">
<Link to="/">Home</Link>
<Link to="/add-employee">Add Employee</Link>
<Link to="/employees">Employee List</Link>
</Nav>
</Navbar.Collapse>
</Container>
</Navbar>
)
}
export default Navigation
The file and folder structure for the frontend part looks like this:
Now, save all the files and run the application:
Hope it helps.