Spring Boot Backend Development Course, Blog Screen Composition Example, Adding Edit and Create Features

Example of Blog Screen Structure and Adding Edit/Create Features

Spring Boot is a Java-based framework that is very popular for backend development of web applications these days. In this course, we will explain the process of developing a simple blog system using Spring Boot step by step. In particular, we will cover in detail examples of blog screen structure and features for editing and creating posts.

1. Starting the Project

First, we use Spring Initializr to start a Spring Boot project. Visit Spring Initializr and set it up as follows:

  • Project: Maven Project
  • Language: Java
  • Spring Boot: 2.5.4 (Select the latest version)
  • Packaging: Jar
  • Java Version: 11
  • Dependencies: Spring Web, Spring Data JPA, H2 Database, Spring Boot DevTools

Once the setup is complete, click the ‘GENERATE’ button to download the project. Unzip the downloaded ZIP file and open the project in your IDE (e.g., IntelliJ IDEA or Eclipse).

2. Creating a Blog Post Entity Model

We define the Post model for the blog we are going to create. To do this, we create a class named `Post` and use JPA annotations to define the structure of the database.

java
@Entity
public class Post {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String title;
    private String content;
    private LocalDateTime createdAt;

    // getter, setter...
}
        

Each field in the Post class you created should have appropriate annotations to grant it the properties of a JPA entity.

3. Creating the Repository

Now, we need to create a repository interface that can handle the `Post` entity. Using JPA, CRUD operations can be easily managed.

java
@Repository
public interface PostRepository extends JpaRepository {
    List findAll();
    Optional findById(Long id);
}
        

4. Setting Up the Service Layer

Later, we will write a service class to handle business logic. The service class will rely on dependency injection from the repository to provide CRUD functionality.

java
@Service
public class PostService {
    private final PostRepository postRepository;

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

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

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

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

    public Post updatePost(Long id, Post postDetails) {
        Post post = getPostById(id);
        if (post != null) {
            post.setTitle(postDetails.getTitle());
            post.setContent(postDetails.getContent());
            return postRepository.save(post);
        }
        return null;
    }

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

5. Setting Up the Controller

Create a controller class that provides a RESTful API to communicate with the frontend. You can use `@RestController` to handle HTTP requests.

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

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

    @GetMapping
    public List getAllPosts() {
        return postService.getAllPosts();
    }

    @GetMapping("/{id}")
    public Post getPost(@PathVariable Long id) {
        return postService.getPostById(id);
    }

    @PostMapping
    public Post createPost(@RequestBody Post post) {
        return postService.createPost(post);
    }

    @PutMapping("/{id}")
    public Post updatePost(@PathVariable Long id, @RequestBody Post post) {
        return postService.updatePost(id, post);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity deletePost(@PathVariable Long id) {
        postService.deletePost(id);
        return ResponseEntity.noContent().build();
    }
}
        

6. Setting Up the H2 Database

We will set up the H2 database for easy use during the development process. Configure it in the `application.properties` file as follows:

properties
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
        

To access the H2 database console, you can use the path /h2-console.

7. Setting Up the Blog Screen

Implement the screen that makes up the blog using HTML and CSS. For example, prepare a detailed page to display the list of posts and each post.

html




    
    Blog


    

Blog Post List

8. Adding Edit/Create Functionality

We will add features that allow users to create and edit blog posts. To do this, we need to implement an HTML form to receive user input.

html

With this code, users can create a new blog post by entering a title and content. Additionally, similar functionality can be implemented to edit existing posts.

9. Conclusion

In this course, we learned how to build a simple blog system using Spring Boot. Through database setup, RESTful API configuration, HTML screen implementation, and adding post creation/editing features, we have gained an understanding of the basics of web applications. Based on this, consider adding more complex features or expanding the project while considering long-term compatibility with other frameworks.

Thank you! I hope your journey in Spring Boot backend development is successful.

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!

Spring Boot Backend Development Course, Blog Screen Composition Example, Implementing Blog Post View

Introduction

Spring Boot is a framework that helps facilitate the rapid development of Java-based applications.
This course covers the essential concepts required for backend development, as well as the basic screen layout and post view implementation of a blog application.
A blog system using Spring Boot includes topics such as RESTful API development, database integration, and security configuration.

Environment Setup

I will explain the development environment and tools required to proceed with the course.
The following tools and libraries must be installed.

  • Java 11 or higher
  • Spring Boot 2.5 or higher
  • IDE (e.g., IntelliJ IDEA, Eclipse, VSCode)
  • MySQL or H2 Database
  • Maven or Gradle

Project Creation

Create a new Spring Boot project using Spring Initializr.
Add the following Spring Boot-related dependencies.

  • Spring Web
  • Spring Data JPA
  • MySQL Driver (if using MySQL)
  • Spring Security
  • Thymeleaf (if used as the frontend template engine)

Blog Screen Layout Example

1. Setting Up Basic URL Path

To set the basic URL path of the blog application, write the following in the application.properties file.

        server.port=8080
        spring.datasource.url=jdbc:mysql://localhost:3306/blogdb
        spring.datasource.username=root
        spring.datasource.password=yourpassword
        spring.jpa.hibernate.ddl-auto=update
    

2. Creating Blog Post Entity

Create a simple Entity class to represent blog posts.

        import javax.persistence.*;
        import java.time.LocalDateTime;

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

            private String title;
            private String content;

            @Column(updatable = false)
            private LocalDateTime createdAt;

            @PrePersist
            protected void onCreate() {
                createdAt = LocalDateTime.now();
            }

            // getters and setters
        }
    

3. Creating Repository Interface

Create a Repository interface for performing CRUD operations on blog posts.

        import org.springframework.data.jpa.repository.JpaRepository;

        public interface BlogPostRepository extends JpaRepository {
        }
    

4. Implementing Service Class

Write a service class to implement business logic.

        import org.springframework.beans.factory.annotation.Autowired;
        import org.springframework.stereotype.Service;

        import java.util.List;

        @Service
        public class BlogPostService {
            @Autowired
            private BlogPostRepository repository;

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

            public BlogPost findById(Long id) {
                return repository.findById(id).orElse(null);
            }

            public void save(BlogPost blogPost) {
                repository.save(blogPost);
            }

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

5. Implementing Controller

Implement a Controller class to handle client requests.
The following is an example that outputs the list of blog posts.

        import org.springframework.beans.factory.annotation.Autowired;
        import org.springframework.stereotype.Controller;
        import org.springframework.ui.Model;
        import org.springframework.web.bind.annotation.GetMapping;

        @Controller
        public class BlogPostController {
            @Autowired
            private BlogPostService blogPostService;

            @GetMapping("/posts")
            public String getAllPosts(Model model) {
                model.addAttribute("posts", blogPostService.findAll());
                return "posts"; // Thymeleaf template file
            }
        }
    

Implementing Blog Post View

In this section, we will implement the blog post view.
We will write a Thymeleaf template to display the list of posts based on the Controller and Service prepared in the previous section.

1. Thymeleaf Setup

Add Thymeleaf settings to the application.properties file.

        spring.thymeleaf.prefix=classpath:/templates/
        spring.thymeleaf.suffix=.html
    

2. Creating Blog Post List Template

Create the src/main/resources/templates/posts.html file and enter the following code.

        

        
        
            Blog Post List
        
        
            

Blog Post List


Conclusion

Through this course, we explored the methods for backend development of a basic blog application using Spring Boot.
Additionally, I recommend implementing more complex features, including authentication, authorization management, and writing test cases.

I will continue the series later to include more content. Thank you!

Spring Boot Backend Development Course, Blog Screen Composition Example, View Testing

Introduction

Spring Boot is a lightweight application framework based on the Spring Framework. With Spring Boot, you can quickly start and run applications without complex configuration. In this course, we will explore backend development using Spring Boot, covering how to create a real application through an example of blog screen composition and how to test views.

1. Setting Up a Development Environment

To start a Spring Boot project, the following tools are required:

  • Java Development Kit (JDK): You should use JDK 8 or higher.
  • IDE: An integrated development environment such as IntelliJ IDEA, Eclipse, or VSCode.
  • Build Tool: You can use Maven or Gradle.

1.1. Creating a Project with Spring Initializr

To save a lot of time and effort, you can use Spring Initializr to create a project. Here are the basic steps for project creation:

  1. Visit the website.
  2. Enter project metadata (Group, Artifact, etc.).
  3. Select the required dependencies (Starters): Spring Web, Spring Data JPA, Spring Boot DevTools, etc. are recommended.
  4. Click the “Generate” button to download the ZIP file.
  5. Extract the downloaded file and import it into your IDE.

2. Understanding Project Structure

Let’s take a look at the basic structure of the generated project:

    └── src
        ├── main
        │   ├── java
        │   │   └── com
        │   │       └── example
        │   │           └── demo
        │   │               ├── DemoApplication.java
        │   │               ├── model
        │   │               ├── repository
        │   │               ├── service
        │   │               └── controller
        │   └── resources
        │       ├── application.properties
        │       └── static
        │       └── templates
        └── test
    

2.1. Role of Each Directory

Each directory has a specific purpose:

  • model: Defines the data model of the application.
  • repository: Contains interfaces for interactions with the database.
  • service: Handles business logic.
  • controller: Processes HTTP requests and sends responses.

3. Example of Blog Screen Composition

Now, let’s compose the screen of a simple blog application. Below is an example of a controller and HTML view for displaying a list of blog posts.

3.1. Creating the Blog Post Model

    package com.example.demo.model;

    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;

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

        // getters and setters
    }
    

3.2. Creating the Blog Repository

    package com.example.demo.repository;

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

    public interface PostRepository extends JpaRepository {}
    

3.3. Creating the Blog Service

    package com.example.demo.service;

    import com.example.demo.model.Post;
    import com.example.demo.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 save(Post post) {
            return postRepository.save(post);
        }
    }
    

3.4. Creating the Blog Controller

    package com.example.demo.controller;

    import com.example.demo.model.Post;
    import com.example.demo.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.PostMapping;
    import org.springframework.web.bind.annotation.RequestMapping;

    import java.util.List;

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

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

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

3.5. Creating the HTML View

Now, let’s create an HTML view. Below is an example of a blog post list view using Thymeleaf:

    
    
        Blog Post List
    
    
        

Blog Post List

Title Content

4. Testing the View

To ensure the application is working correctly, view tests must be performed. Spring Boot provides various tools to easily conduct integration tests.

4.1. Setting Up the Test Environment

First, the spring-boot-starter-test dependency must be included. Add the following to your pom.xml file:

    
        org.springframework.boot
        spring-boot-starter-test
        test
    
    

4.2. Creating Integration Tests

Next, let’s create a test class for the controller:

    package com.example.demo;

    import com.example.demo.model.Post;
    import com.example.demo.repository.PostRepository;
    import com.example.demo.service.PostService;
    import org.junit.jupiter.api.BeforeEach;
    import org.junit.jupiter.api.Test;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
    import org.springframework.boot.test.mock.mockito.MockBean;
    import org.springframework.test.web.servlet.MockMvc;

    import java.util.Arrays;
    import java.util.List;

    import static org.mockito.ArgumentMatchers.any;
    import static org.mockito.Mockito.when;
    import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
    import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
    import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
    import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;

    @WebMvcTest(PostController.class)
    public class PostControllerTest {
        @Autowired
        private MockMvc mockMvc;

        @MockBean
        private PostService postService;

        @BeforeEach
        public void setup() {
            List posts = Arrays.asList(
                new Post(1L, "First Post", "Content 1"),
                new Post(2L, "Second Post", "Content 2")
            );

            when(postService.findAll()).thenReturn(posts);
        }

        @Test
        public void testList() throws Exception {
            mockMvc.perform(get("/posts"))
                .andExpect(status().isOk())
                .andExpect(view().name("posts/list"))
                .andExpect(model().attributeExists("posts"));
        }

        @Test
        public void testCreate() throws Exception {
            mockMvc.perform(post("/posts")
                .param("title", "New Post")
                .param("content", "Content"))
                .andExpect(status().is3xxRedirection())
                .andExpect(redirectedUrl("/posts"));
        }
    }
    

4.3. Running the Tests

Running the above tests will confirm that the blog post listing and new post creation features are functioning correctly.

Conclusion

In this course, we explored backend development of a blog application using Spring Boot, covering how to set up the model, repository, service, controller, and HTML view necessary for building a real application. We also learned how to test the views we created. Through this course, I hope you will build a solid foundation to create powerful web applications using Spring Boot.

References