Spring Boot Backend Development Course, Blog Screen Composition Example, Prerequisites Thymeleaf

Hello! Today, we will learn in detail about how to develop the backend of a blog using Spring Boot. In this course, we will cover examples for the basic screen configuration of the blog and learn how to utilize Spring Boot and Thymeleaf through hands-on practice.

Course Objectives

  • Understand the basic structure of Spring Boot
  • Build dynamic web pages using Thymeleaf
  • Implement basic CRUD functionalities for the blog
  • Learn the basics of API design and database integration

Prerequisites: Thymeleaf

Thymeleaf is a template engine for creating views in web applications using Java. It is based on HTML and performs a role similar to JSP but offers more features and flexibility. Some of the advantages of Thymeleaf include:

  • Natural templates: The written template is valid as a regular HTML file.
  • Diverse view options: Supports various views such as HTML, XML, JavaScript, CSS, etc.
  • Both server-side and client-side processing are possible.

Setting Up a Spring Boot Project

First, let’s learn how to set up a Spring Boot project. You can create a new project using IntelliJ IDEA or Spring Initializr.

1. Access Spring Initializr: https://start.spring.io/
2. Choose Project: Gradle Project
3. Choose Language: Java
4. Select Spring Boot: Version 2.5.4 or higher
5. Enter Project Metadata:
   - Group: com.example
   - Artifact: blog
6. Add Dependencies:
   - Spring Web
   - Spring Data JPA
   - H2 Database
   - Thymeleaf
7. Click Generate to download the project

Project Structure

When you create the project, a basic file structure will be generated. Understanding this structure is important.

  • src/main/java: This folder contains the Java source code.
  • src/main/resources: This folder contains static resources and template files, including the application.properties file.
  • src/test/java: This folder contains the test code.

Setting Up the Blog Model

In this blog application, we will primarily set up a Post model. We define the Post model using the following steps.

package com.example.blog.model;

import javax.persistence.*;

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

    private String title;
    private String content;

    // Constructor, Getters, Setters
    public Post() {}

    public Post(String title, String content) {
        this.title = title;
        this.content = content;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
}

Database Configuration

You can simply store data using the H2 database. Configure the database settings in the application.properties file as follows.

spring.h2.console.enabled=true
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect

Creating the Repository Interface

To easily interact with the database using JPA, we create a Repository interface.

package com.example.blog.repository;

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

public interface PostRepository extends JpaRepository {
}

Creating the Service Class

The service class is where the business logic is processed. It includes CRUD functionalities for posts.

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 {
    @Autowired
    private PostRepository postRepository;

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

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

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

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

Creating the Controller Class

The Spring MVC controller handles web requests. It includes methods to return a list of posts and to add a new post.

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.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;

@Controller
public class PostController {
    @Autowired
    private PostService postService;

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

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

    @PostMapping("/post")
    public String savePost(@ModelAttribute Post post) {
        postService.save(post);
        return "redirect:/";
    }
}

Creating Thymeleaf Templates

Finally, we will create Thymeleaf template files to build the blog’s interface. We will draft the basic HTML file and explore how to output data.

Post List Screen

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

Post Creation Screen

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Create New Post</title>
</head>
<body>
    <h1>Create New Post</h1>
    <form action="#" th:action="@{/post}" th:object="${post}" method="post">
        <label for="title">Title:</label>
        <input type="text" id="title" th:field="*{title}" required/>
        <br/>
        <label for="content">Content:</label>
        <textarea id="content" th:field="*{content}" required></textarea>
        <br/>
        <button type="submit">Submit</button>
    </form>
    <a href="@{/}">Go Back to List</a>
</body>
</html>

Conclusion

In this course, we explored backend development using Spring Boot and the creation of a simple blog interface with Thymeleaf. Through this example, we gained an understanding of the basic workings of Spring Boot and learned how to create dynamic web pages using Thymeleaf.

Furthermore, based on this example, feel free to add various features or apply different design patterns. You will learn a lot during the process of developing a real application using Spring Boot and Thymeleaf.

Thank you!