Fetch from HTML template in spring boot

2 min read 22-09-2024
Fetch from HTML template in spring boot


Spring Boot is a popular framework for building Java applications. One of its powerful features is the ability to serve dynamic web pages using HTML templates. In this article, we will explore how to fetch data and render it in an HTML template with Spring Boot.

Problem Scenario

Imagine you are developing a web application where you want to display a list of users on a webpage. To do this, you need to retrieve user data from a backend service and present it using an HTML template. Here’s a simplified version of what this code might look like:

Original Code Snippet

@Controller
public class UserController {
    
    @GetMapping("/users")
    public String getUsers(Model model) {
        List<User> userList = userService.getAllUsers(); // Fetching users from the service
        model.addAttribute("users", userList);
        return "userList"; // Returning the HTML template name
    }
}

In the above code, we have a UserController that handles requests to the /users URL, fetching user data and passing it to the userList HTML template.

How It Works

  1. Controller: The @Controller annotation tells Spring that this class serves as a controller in the MVC pattern. The getUsers method is responsible for processing requests to /users.

  2. Service Layer: The method calls a service to retrieve a list of users. It’s assumed that userService.getAllUsers() returns a list of User objects.

  3. Model: The Model parameter allows us to add attributes to the view. In this case, we are adding the list of users to the model with the name "users".

  4. View Resolution: Finally, we return "userList", which is the name of the HTML template that will be rendered.

HTML Template Example

Let's say we have an HTML file named userList.html located in src/main/resources/templates:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>User List</title>
</head>
<body>
    <h1>User List</h1>
    <ul>
        <th:block th:each="user : ${users}">
            <li th:text="${user.name}">User Name</li>
        </th:block>
    </ul>
</body>
</html>

In this template, we are using Thymeleaf, a popular templating engine for Spring Boot applications. The th:each attribute iterates over the "users" model attribute and displays each user's name.

Practical Example: Full Implementation

Here is a complete example for clarity:

User Model

public class User {
    private String name;

    // Constructor, getters and setters
    public User(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

User Service

@Service
public class UserService {
    public List<User> getAllUsers() {
        // In a real application, this would come from a database
        return List.of(new User("Alice"), new User("Bob"), new User("Charlie"));
    }
}

User Controller (Revised)

@Controller
public class UserController {
    
    @Autowired
    private UserService userService;

    @GetMapping("/users")
    public String getUsers(Model model) {
        List<User> userList = userService.getAllUsers(); 
        model.addAttribute("users", userList);
        return "userList"; 
    }
}

Conclusion

In this article, we explored how to fetch and render data using HTML templates in Spring Boot. We implemented a basic user list feature, demonstrating the integration of the controller, service, and HTML template.

Additional Resources

By following these steps, you can effectively use Spring Boot to build dynamic web applications that serve data to HTML templates, enhancing user experience and interaction.