Spring Boot Backend Development Course, Blog Screen Layout Example, Writing Controllers for Learning Thymeleaf Syntax

1. Overview

This course helps to provide a basic understanding of backend development using Spring Boot and explains how to learn Thymeleaf syntax through a blog screen composition example.

Spring Boot is a Java-based web application framework that helps you create web applications quickly and easily without complex configurations. This allows developers to focus on business logic and increase productivity.

2. Tech Stack

The main tech stack used in this course includes:

  • Java 11 or higher
  • Spring Boot 2.x
  • Thymeleaf
  • Spring Data JPA
  • H2 Database

This tech stack forms a strong combination for backend development. A brief description of each tech stack is as follows.

  • Java: An object-oriented programming language that is platform-independent.
  • Spring Boot: A framework that simplifies configuration and deployment in Java Spring.
  • Thymeleaf: An HTML5 template engine used for composing views.
  • Spring Data JPA: A library that makes it easier to interact with the database.
  • H2 Database: A lightweight, in-memory database suitable for testing and prototyping.

3. Project Setup

To set up a Spring Boot project, use Spring Initializr. Access Spring Initializr and configure the following settings:

  • Project: Maven Project
  • Language: Java
  • Spring Boot: 2.x
  • Group: com.example
  • Artifact: blog
  • Dependencies: Spring Web, Thymeleaf, Spring Data JPA, H2 Database

Save the above settings and download the project. Then import it in your IDE to start working.

4. Create Entity Class

Create entity classes to define the data models needed for the application. To store basic blog posts, the Post entity class is created as follows:

package com.example.blog.model;

import javax.persistence.*;

@Entity
public class Post {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String title;

    @Column(nullable = false)
    private String content;

    private String author;

    // getters and setters
}

This class contains the ID, title, content, and author of the post. It handles the mapping to the database using JPA.

5. Create Repository Interface

Create a repository interface that extends JpaRepository to handle CRUD operations for the Post entity:

package com.example.blog.repository;

import com.example.blog.model.Post;
import org.springframework.data.jpa.repository.JpaRepository;

public interface PostRepository extends JpaRepository {
}

This interface allows easy access to CRUD operations associated with the Post entity in the database.

6. Write Service Class

Create a service class that handles business logic and defines business rules. The PostService class is written as follows:

package com.example.blog.service;

import com.example.blog.model.Post;
import com.example.blog.repository.PostRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PostService {
    private final PostRepository postRepository;

    @Autowired
    public PostService(PostRepository postRepository) {
        this.postRepository = postRepository;
    }

    public List findAll() {
        return postRepository.findAll();
    }

    public Post save(Post post) {
        return postRepository.save(post);
    }

    public Post findById(Long id) {
        return postRepository.findById(id).orElse(null);
    }

    public void deleteById(Long id) {
        postRepository.deleteById(id);
    }
}

This class defines methods to retrieve the list of posts, save posts, and delete posts.

7. Write Controller

Now, let’s write the controller class to handle client requests. The PostController class can be written as follows:

package com.example.blog.controller;

import com.example.blog.model.Post;
import com.example.blog.service.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/posts")
public class PostController {
    private final PostService postService;

    @Autowired
    public PostController(PostService postService) {
        this.postService = postService;
    }

    @GetMapping
    public String list(Model model) {
        List posts = postService.findAll();
        model.addAttribute("posts", posts);
        return "post/list";
    }

    @GetMapping("/new")
    public String createForm(Model model) {
        model.addAttribute("post", new Post());
        return "post/form";
    }

    @PostMapping
    public String create(Post post) {
        postService.save(post);
        return "redirect:/posts";
    }
    
    @GetMapping("/{id}")
    public String view(@PathVariable Long id, Model model) {
        Post post = postService.findById(id);
        model.addAttribute("post", post);
        return "post/view";
    }

    @GetMapping("/edit/{id}")
    public String editForm(@PathVariable Long id, Model model) {
        Post post = postService.findById(id);
        model.addAttribute("post", post);
        return "post/form";
    }

    @PostMapping("/edit/{id}")
    public String edit(@PathVariable Long id, Post post) {
        post.setId(id);
        postService.save(post);
        return "redirect:/posts";
    }

    @GetMapping("/delete/{id}")
    public String delete(@PathVariable Long id) {
        postService.deleteById(id);
        return "redirect:/posts";
    }
}

The controller defines handler methods for HTTP requests following the pattern. The above code implements listing, creating, editing, and deleting posts functionalities.

8. Write Thymeleaf Template

Now it’s time to create the HTML view using Thymeleaf. The list.html to display the list of posts can be written as follows:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Post List</title>
</head>
<body>
    <h1>Post List</h1>
    <a href="@{/posts/new}">Create New Post</a>
    <ul>
        <li th:each="post : ${posts}">
            <a th:href="@{/posts/{id}(id=${post.id})}">[[${post.title}]]</a>
        </li>
    </ul>
</body>
</html>

The above template displays the list of posts, where clicking on each post title will take you to the details page of that post.

9. Conclusion

This course introduced how to build a simple blog application using Spring Boot and Thymeleaf. I hope it helped you understand basic backend development by creating entity, repository, service, controller, and view step by step.

If you want to add more features, consider implementing comment functionality for posts, user authentication, and permission management. This will help you build a solid foundation for more advanced web application development.