Skip to main content

Command Palette

Search for a command to run...

Building Full-Stack Applications with Spring Boot and React

Week-04

Updated
5 min read

As we wrap up Week 4 of our Spring Boot learning journey, we’ve moved from theory to practical implementation! This week’s focus was on building a full-stack application using Spring Boot for the backend and React for the frontend. The concepts covered are crucial for creating real-world applications that manage data and offer user-friendly interfaces.


Topics Covered

  1. Understanding React Frontend

  2. Setting Up a Spring Boot Project with Models

  3. Loading Data into H2 Database

  4. Handling CORS Errors in Spring Boot

  5. Using Response Entity and Fetching Data by ID

  6. Adding Products with Images

  7. Fetching Images from the Server

  8. Updating and Deleting Products

  9. Implementing a Search Feature


1. Understanding React Frontend

To build a complete application, you need a frontend to interact with users. React, a JavaScript library, is perfect for creating dynamic, component-based UIs. This video introduced the basics of React, including how to:

  • Create components (UI elements like forms or buttons).

  • Use props to pass data between components.

  • Manage state to handle dynamic data in your app.

React acts as the view layer of your application, connecting seamlessly to the Spring Boot backend.


2. Setting Up a Spring Boot Project with Models

The backend starts with defining models, which represent your database entities. In this video, the instructor walked through:

  • Setting up a Spring Boot project with Maven dependencies.

  • Creating JPA entities with annotations like @Entity and @Id.

  • Structuring the project with controllers, services, and repositories for clean code.

Example:

@Entity
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private Double price;

    // Getters and Setters
}

This sets the foundation for managing data in your application.


3. Loading Data into H2 Database

Using the H2 in-memory database, you can quickly load and test data. This step is essential for rapid prototyping. Key steps included:

  • Adding H2 dependency in pom.xml.

  • Configuring application.properties to enable H2.

  • Loading sample data into the database using Spring Boot’s data.sql file.

Configuration Example:

spring.datasource.url=jdbc:h2:mem:testdb
spring.h2.console.enabled=true

4. Handling CORS Errors in Spring Boot

When connecting React (frontend) to Spring Boot (backend), CORS (Cross-Origin Resource Sharing) errors can occur. This happens when the frontend and backend are hosted on different servers. The instructor demonstrated how to fix this by enabling CORS in Spring Boot.

Solution Example:

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedOrigins("http://localhost:3000");
    }
}

This configuration allows your React app to make API calls to the backend.


5. Using ResponseEntity and Fetching Data by ID

The ResponseEntity class in Spring Boot provides more control over HTTP responses. It lets you define:

  • Status codes (e.g., 200 OK, 404 Not Found).

  • Response headers.

  • Response bodies.

Example:

@GetMapping("/{id}")
public ResponseEntity<Product> getProductById(@PathVariable Long id) {
    Optional<Product> product = productRepository.findById(id);
    return product.map(ResponseEntity::ok)
                  .orElse(ResponseEntity.notFound().build());
}

6. Adding Products with Images

To add products with images, the backend needs to handle multipart file uploads. Key steps included:

  1. Using @RequestParam to accept image files in the controller.

  2. Saving the image data (as a file or in the database).

Example:

@PostMapping("/products")
public Product addProduct(@RequestParam("file") MultipartFile file, @RequestParam("name") String name) {
    // Logic to save product and file
}

7. Fetching Images from the Server

Once images are saved, the backend needs to provide an endpoint to fetch them. This involves:

  • Storing image paths in the database.

  • Returning images as byte streams using Spring Boot.

Example:

@GetMapping("/products/{id}/image")
public ResponseEntity<byte[]> getProductImage(@PathVariable Long id) {
    byte[] image = productService.getProductImage(id);
    return ResponseEntity.ok().contentType(MediaType.IMAGE_JPEG).body(image);
}

8. Updating and Deleting Products

The backend needs endpoints to modify or delete existing records.

  • PUT Method: Updates a product’s details.

  • DELETE Method: Removes a product from the database.

Example:

@PutMapping("/{id}")
public Product updateProduct(@PathVariable Long id, @RequestBody Product product) {
    return productService.updateProduct(id, product);
}

@DeleteMapping("/{id}")
public void deleteProduct(@PathVariable Long id) {
    productService.deleteProduct(id);
}

9. Implementing a Search Feature

Finally, a search feature allows users to find products based on specific criteria, such as name or price. The instructor demonstrated using custom query methods in Spring Data JPA.

Example:

public interface ProductRepository extends JpaRepository<Product, Long> {
    List<Product> findByNameContaining(String name);
}

This query retrieves all products with names matching the input string.


Real-World Example: Product Management System

Imagine building a product management system for an online store. Here’s how the features come together:

  1. Frontend (React): Users can view, add, update, delete, and search for products.

  2. Backend (Spring Boot): Handles API requests for managing product data and serving images.

  3. Database (H2): Stores product details and paths to uploaded images.

This project is a practical implementation of all the concepts we’ve learned.


References

  1. Spring Framework Documentation

  2. Spring Boot Documentation

  3. Spring and Spring Boot Tutorial Playlist by Navin Sir


Wrapping Up

This week, we turned theory into practice by building a full-stack product management application.

Key Takeaways:

  • React is an excellent choice for building dynamic frontends.

  • Spring Boot provides a powerful backend for managing data and handling business logic.

  • Understanding CORS, HTTP methods, and file uploads is essential for full-stack development.

  • With Spring Data JPA, interacting with databases becomes effortless.

By combining these skills, you’re ready to build scalable, real-world web applications. Stay tuned for more insights in Week 5! 🚀

LinkedIn- LinkedIn Post

GitHub- Codebase

Happy coding !!😊