Are you looking to dive into full-stack web development using Java Spring Boot and React? In this guide, we will cover the basics of setting up a full-stack web application with Java Spring Boot as the backend and React as the frontend.
Getting Started with Java Spring Boot
First, let's set up our backend using Java Spring Boot. Here's a simple example of a REST controller in Spring Boot:
@RestController
@RequestMapping("/api")
public class ApiController {
@GetMapping("/hello")
public String sayHello() {
return "Hello, world!";
}
}
This controller exposes a GET endpoint at /api/hello
that returns a simple message.
Setting Up React for the Frontend
Next, let's set up our frontend using React. Here's a basic example of a React component that fetches data from our backend API:
import React, { useEffect, useState } from 'react';
function App() {
const [message, setMessage] = useState('');
useEffect(() => {
fetch('/api/hello')
.then(response => response.text())
.then(data => setMessage(data));
}, []);
return (
<div>
<h1>{message}</h1>
</div>
);
}
export default App;
Bringing It All Together
To connect our frontend to our backend, we need to start both the Spring Boot server and the React development server. By proxying API requests from React to the backend, we can seamlessly integrate the two technologies.
// package.json
{
"proxy": "http://localhost:8080"
}
With this setup, you can build full-stack web applications using Java Spring Boot and React. Happy coding!