Building Web Applications with Spring and Spring Boot

Week-03


As we wrap up Week 3 of exploring Spring and Spring Boot, we’ve taken a deep dive into building web applications, managing HTTP requests, and working with Spring Data JPA. These are essential skills for developing modern Java applications.

In this blog, I’ll explain the key concepts covered this week in a beginner-friendly manner, with practical examples to help you apply what you learn.


Topics Covered

  1. Spring Boot Web

  2. Spring MVC and Layers

  3. HTTP Methods: GET and POST in Spring Web

  4. HTTP Methods: PUT and DELETE in Spring Web

  5. Introduction to Spring Data JPA

  6. Setting Up Spring Data JPA with H2 Database

  7. Spring Data JPA and JpaRepository


1. Spring Boot Web

Spring Boot makes creating web applications easier than ever by embedding a web server (like Tomcat) and providing ready-to-use configurations. With Spring Boot, you can quickly set up web endpoints to handle requests from users.

In a Spring Boot web application, we use controllers to define endpoints (URLs) that process user requests and return responses. This is the foundation of REST APIs.

Example:
Let’s create a simple "Hello, World!" endpoint:

@RestController
@RequestMapping("/api")
public class HelloController {

    @GetMapping("/hello")
    public String sayHello() {
        return "Hello, World!";
    }
}

Here:

  • @RestController defines a RESTful controller.

  • @GetMapping maps HTTP GET requests to the sayHello method, which returns the response.

This endpoint will respond with "Hello, World!" when accessed via /api/hello.


2. Spring MVC and Layers

Spring MVC (Model-View-Controller) is an architecture that organizes your code into three main components:

  1. Model: Represents the application’s data (e.g., database records).

  2. View: Handles the presentation layer (e.g., HTML templates or JSON responses).

  3. Controller: Manages user requests and updates the Model or View as needed.

This separation of concerns keeps your code clean, modular, and easy to maintain.

Example:
Here’s how a simple MVC flow looks:

@Controller
public class HomeController {

    @GetMapping("/home")
    public String home(Model model) {
        model.addAttribute("message", "Welcome to the Home Page!");
        return "home";
    }
}
  • @Controller marks the class as a controller.

  • Model allows you to pass data to the view.

  • The home method maps the /home URL to a template called home.html, displaying the message.


3. HTTP Methods: GET and POST in Spring Web

HTTP methods define how requests interact with your web server.

  • GET: Used to retrieve data.

  • POST: Used to submit new data to the server.

These methods form the backbone of RESTful APIs.

Example:
Let’s handle GET and POST requests:

@RestController
@RequestMapping("/users")
public class UserController {

    @GetMapping("/{id}")
    public User getUser(@PathVariable Long id) {
        // Retrieve and return user by ID
    }

    @PostMapping
    public User createUser(@RequestBody User user) {
        // Create and return new user
    }
}
  • @PathVariable extracts the user ID from the URL.

  • @RequestBody binds JSON data from the request body to the user object.


4. HTTP Methods: PUT and DELETE in Spring Web

In addition to GET and POST, REST APIs often need to update or delete resources.

  • PUT: Updates an existing resource.

  • DELETE: Removes a resource.

Example:
Here’s how PUT and DELETE requests are handled:

@PutMapping("/{id}")
public User updateUser(@PathVariable Long id, @RequestBody User user) {
    // Update user by ID and return updated user
}

@DeleteMapping("/{id}")
public void deleteUser(@PathVariable Long id) {
    // Delete user by ID
}

These methods allow your application to manage resources dynamically, making it more interactive.


5. Introduction to Spring Data JPA

Spring Data JPA simplifies working with databases by providing easy-to-use methods for CRUD operations.

Instead of writing SQL queries, you define Java methods in a repository interface, and Spring does the heavy lifting.

Example:
Here’s how to define an entity and its repository:

@Entity
public class Product {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private Double price;

    // Getters and setters
}

public interface ProductRepository extends JpaRepository<Product, Long> {
    // Spring provides basic CRUD operations out of the box
}
  • @Entity marks the class as a database entity.

  • JpaRepository provides CRUD methods like save(), findById(), and deleteById() for Product.


6. Setting Up Spring Data JPA with H2 Database

H2 is an in-memory database perfect for development and testing. It’s easy to set up with Spring Boot.

Steps to Configure:

  1. Add the H2 dependency to pom.xml:

     <dependency>
         <groupId>com.h2database</groupId>
         <artifactId>h2</artifactId>
         <scope>runtime</scope>
     </dependency>
    
  2. Configure H2 in application.properties:

     spring.datasource.url=jdbc:h2:mem:testdb
     spring.datasource.driver-class-name=org.h2.Driver
     spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
    
  3. Start using your repository interface to interact with the database.


7. Spring Data JPA and JpaRepository

The JpaRepository interface extends basic CRUD operations and allows you to create custom queries for your application’s needs.

Example:
Let’s create a custom query to find products by name:

public interface ProductRepository extends JpaRepository<Product, Long> {

    List<Product> findByName(String name);
}

Spring will automatically implement this method for you, making it easy to fetch products by their name.


Real-World Example: Product Management API

Imagine a simple product management system for an e-commerce app.

  • GET /products: List all products.

  • POST /products: Add a new product.

  • PUT /products/{id}: Update product details.

  • DELETE /products/{id}: Remove a product.

Using Spring Boot Web and Spring Data JPA, you can build this API in minutes by defining a ProductController and connecting it to your ProductRepository.


References

  1. Spring Framework Documentation

  2. Spring Boot Documentation

  3. Spring Boot Tutorial - YouTube Playlist by Navin Sir


Wrapping Up

This week, we explored building web applications with Spring Boot, managing HTTP requests, and using Spring Data JPA for database interactions.

Key Takeaways:

  • Spring Boot simplifies web application development with embedded servers and pre-configured tools.

  • Spring MVC organizes your application into layers, making it modular and maintainable.

  • HTTP methods like GET, POST, PUT, and DELETE form the backbone of REST APIs.

  • Spring Data JPA and H2 make database interactions easy and efficient.

By practicing these concepts, you’ll be able to create scalable and interactive Java applications. Stay tuned for more insights in Week 4! 🚀

LinkedIn- LinkedIn Post

GitHub- Codebase

Happy coding!😊