Spring Boot Backend Development Course, Blog Screen Layout Example, Creating HTML View

Introduction

In this course, we will learn how to develop a backend web application using Spring Boot. Spring Boot is a framework that helps build Spring applications quickly without complex configurations. This course will particularly use a blog web application as an example, and we will explain in detail about screen composition and creating HTML views.

Table of Contents

  • What is Spring Boot?
  • Blog Screen Composition
  • Project Setup
  • Creating HTML Views
  • Testing and Deployment

What is Spring Boot?

Spring Boot is a project built on the Spring Framework that simplifies the configuration of traditional Spring applications, allowing developers to quickly create and deploy prototypes. The main features of Spring Boot are as follows:

  • Auto-configuration: Spring Boot performs many configurations automatically by default, preventing developers from being tied down by complex settings.
  • Starter Dependencies: It helps easily add required dependencies with a single declaration.
  • Embedded Server: By using embedded servers such as Tomcat and Jetty, applications can be run without separate server setups.
  • Easy Profile Management: It provides the ability to configure settings differently as needed in various environments.

Blog Screen Composition

The structure of the blog application is very simple. It basically consists of pages where users can view and create posts. Additionally, each post can include features such as comments and tags. In this course, we will be creating a simple screen layout.

Screen Components

  • Header: Includes the blog title and logo, along with the navigation menu.
  • Post List: Displays a preview of the title, author, creation date, and content.
  • Post Detail View: Shows the content and comments of the selected post.
  • Footer: Provides copyright information and additional information about the blog.

Project Setup

The project we will use in this course is based on Spring Boot and manages required dependencies using Maven. First, we will add the necessary dependencies to the `pom.xml` file.


<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>runtime</scope>
    </dependency>
</dependencies>
    

Creating HTML Views

HTML views play an important role in displaying data to users. In Spring Boot, we can create dynamic HTML views using Thymeleaf. Below is an example showing the basic HTML structure of a blog.

Basic Layout of the Blog


<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Blog Title</title>
    <link rel="stylesheet" th:href="@{/css/style.css}" />
</head>
<body>

    <header>
        <h1>My Blog</h1>
        <nav>
            <a th:href="@{/}">Home</a>
            <a th:href="@{/posts}">Post List</a>
            <a th:href="@{/new}">Create Post</a>
        </nav>
    </header>

    <main>
        <section class="posts">
            <h2>Recent Posts</h2>
            <div th:each="post : ${posts}">
                <h3 th:text="${post.title}"></h3>
                <p>Author: <span th:text="${post.author}"></span> | <span th:text="${post.createdDate}"></span></p>
                <p th:text="${post.content}"></p>
                <a th:href="@{/posts/{id}(id=${post.id})}">View More</a>
            </div>
        </section>
    </main>

    <footer>
        <p>Copyright © 2023 My Blog</p>
    </footer>

</body>
</html>
    

Post Detail View


<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Post Detail View</title>
    <link rel="stylesheet" th:href="@{/css/style.css}" />
</head>
<body>

    <header>
        <h1 th:text="${post.title}"></h1>
        <nav>
            <a th:href="@{/}">Home</a>
            <a th:href="@{/posts}">Post List</a>
        </nav>
    </header>

    <main>
        <article>
            <h2 th:text="${post.title}"></h2>
            <p>Author: <span th:text="${post.author}"></span> | <span th:text="${post.createdDate}"></span></p>
            <p th:text="${post.content}"></p>
        </article>

        <h3>Comments</h3>
        <div th:each="comment : ${post.comments}">
            <p><span th:text="${comment.author}"></span>: <span th:text="${comment.content}"></span></p>
        </div>

        <h3>Write a Comment</h3>
        <form th:action="@{/posts/{id}/comments(id=${post.id})}" method="post">
            <input type="text" name="author" placeholder="Author" required />
            <textarea name="content" placeholder="Enter your comment" required></textarea>
            <button type="submit">Submit Comment</button>
        </form>
    </main>

    <footer>
        <p>Copyright © 2023 My Blog</p>
    </footer>

</body>
</html>
    

Testing and Deployment

After writing the Spring Boot application, testing and deployment stages are important. Spring Boot supports unit testing using JUnit and Mockito. Moreover, it can be easily deployed using AWS, Heroku, and other cloud services.

Unit Test Example


import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

public class PostControllerTest {

    @InjectMocks
    private PostController postController;

    @Mock
    private PostService postService;

    @Autowired
    private MockMvc mockMvc;

    @BeforeEach
    public void setup() {
        MockitoAnnotations.openMocks(this);
        mockMvc = MockMvcBuilders.standaloneSetup(postController).build();
    }

    @Test
    public void testGetPost() throws Exception {
        // Mock setup to return post information
        when(postService.getPostById(1L)).thenReturn(new Post(1L, "Test Title", "Author", "Content"));

        mockMvc.perform(get("/posts/1"))
            .andExpect(status().isOk())
            .andExpect(model().attributeExists("post"))
            .andExpect(view().name("post/view"));
    }
}
    

Conclusion

In this course, we learned how to build the backend of a blog application using Spring Boot and how to create basic HTML views. We were able to develop efficiently by leveraging the advantages of Spring Boot. Through practical exercises, we understood the basic principles of Spring Boot and Thymeleaf, laying the groundwork to apply them in real projects. I hope to add more features and broaden my understanding of Spring Boot by applying it to various projects in the future.

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

Blog Layout Example, Creating and Testing HTML View

Author: [Name]

Publication Date: [Date]

1. Introduction

Spring Boot is a Java-based web framework that helps developers quickly build applications. In this course, we will cover how to develop the backend of a blog application using Spring Boot and create HTML views for testing.

We will learn how to design RESTful APIs, manage data exchange with clients, and provide visual content to users through HTML views. Through this, we will gain an overall understanding of Spring Boot and the structure of web applications.

2. Setting Up the Development Environment

The process of setting up a development environment using Spring Boot is as follows:

  1. Install JDK: Spring Boot is implemented in Java, so you must install the Java Development Kit (JDK). JDK 11 or higher is recommended.
  2. Set up an IDE: Install an Integrated Development Environment (IDE) such as IntelliJ IDEA or Eclipse.
  3. Create a Spring Boot Project: Use Spring Initializr to create a new Spring Boot project.

3. Creating a Spring Boot Project

Here’s how to create a project using Spring Initializr:

  1. Go to Spring Initializr.
  2. Project: Choose (Maven Project or Gradle Project)
  3. Language: Java
  4. Spring Boot: Select the latest version
  5. Fill in Project Metadata: Group, Artifact, Name, Description, etc.
  6. Select Spring Web, Thymeleaf in Dependencies
  7. Click the Generate button to download the project
  8. Open the downloaded zip file in your IDE

4. Adding Dependencies

To manage the dependencies required for the application you are developing, you will need to modify the build.gradle or pom.xml file. Generally, libraries such as Spring, JPA, and Thymeleaf are added.

5. Designing the RESTful API

Design the RESTful API for the blog application. The goal is to design an API that provides basic CRUD (Create, Read, Update, Delete) functionalities.

5.1. Defining the Domain Model

To manage the blog posts, we define a Post entity:


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

    private String title;
    private String content;
    private LocalDateTime createdAt;

    // Getter and Setter
}

5.2. Creating the Repository Interface

Create a repository for interacting with the database through Spring Data JPA:


@Repository
public interface PostRepository extends JpaRepository {
    List findAll();
}

5.3. Creating the Service Class

Implement a service class to handle business logic:


@Service
public class PostService {
    private final PostRepository postRepository;

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

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

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

5.4. Creating the Controller Class

Implement a controller class to handle HTTP requests:


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

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

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

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

6. Creating HTML View

Let’s look at how to create an HTML view using Thymeleaf in Spring Boot.

6.1. Creating HTML Template

Create an HTML file in the src/main/resources/templates folder. For example, create home.html:






    Blog Home


    

Blog Post List

6.2. Adding Method to Return HTML View in Controller

Add a method in the controller to return the HTML view:


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

7. Testing and Running

Run the application and check the HTTP requests in a web browser to ensure the features are functioning correctly.

  1. Run the application in the IDE to start the Spring Boot application.
  2. Access http://localhost:8080/home in the browser to check the HTML view.
  3. Test the RESTful API using Postman.

8. Conclusion

In this course, we learned how to develop the backend of a blog application using Spring Boot. We gained basic usage of Spring Boot through designing RESTful APIs, creating HTML views, and testing them.

Now you can develop your own various web applications based on Spring Boot. You will be able to implement more complex applications by leveraging the various features of Spring Boot.

Spring Boot Backend Development Course, Blog Creation Example, Preparing for a Project

This course guides you through the process of creating a simple blog using Spring Boot. Spring Boot is a framework developed in Java that helps you build web applications easily and quickly. In this course, you will cover project setup, database configuration, RESTful API implementation, authentication and authorization, and client integration step by step. Through this article, you can learn a wide range of topics from the basics to advanced concepts of Spring Boot.

1. Preparing the Project

1.1 Introduction to Spring Boot

Spring Boot is one of the projects of the Spring framework that allows you to develop applications quickly without complex configurations. The main advantages of Spring Boot are as follows:

  • Reduced complexity related to changes
  • Increased productivity through automatic configuration
  • Suitable for microservices architecture
  • Uses an embedded WAS (Web Application Server)

1.2 Setting Up the Development Environment

Before starting the project, you need to set up the development environment. Install the following tools:

  • Java Development Kit (JDK) – Java 11 or higher recommended
  • IDE – IntelliJ IDEA, Eclipse, or Spring Tool Suite
  • Gradle or Maven – build tools for dependency management
  • Database – MySQL, PostgreSQL, etc.

1.3 Creating a Spring Boot Project

You can use Spring Initializr to create a Spring Boot project. Use the following settings to generate it:

  • Project: Maven Project
  • Language: Java
  • Spring Boot: 2.5.x (or latest version)
  • Group: com.example
  • Artifact: blog
  • Dependencies: Spring Web, Spring Data JPA, MySQL Driver, Spring Security

When you open the generated project in your IDE, you will see that the basic directory structure has been created.

2. Database Configuration

2.1 Installing MySQL

Install MySQL and create a database. Let’s create a database with the following command:

CREATE DATABASE blogdb;

2.2 Configuring application.properties

Open the src/main/resources/application.properties file and set the database connection information:

spring.datasource.url=jdbc:mysql://localhost:3306/blogdb
spring.datasource.username=root
spring.datasource.password=yourpassword
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true

2.3 Creating JPA Entities

Next, create an entity class to store the blog’s data. For example, the Post entity can be written as follows:

package com.example.blog.model;

import javax.persistence.*;

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

    @Column(nullable = false)
    private String title;

    @Column(nullable = false)
    private String content;

    // Getters and Setters
}

3. Implementing RESTful API

3.1 Defining the Controller Class

To manage blog posts, create the PostController class:

package com.example.blog.controller;

import com.example.blog.model.Post;
import com.example.blog.repository.PostRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/posts")
public class PostController {

    @Autowired
    private PostRepository postRepository;

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

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

    @GetMapping("/{id}")
    public ResponseEntity getPostById(@PathVariable Long id) {
        Post post = postRepository.findById(id)
                .orElseThrow(() -> new ResourceNotFoundException("Post not found with id " + id));
        return ResponseEntity.ok(post);
    }

    @PutMapping("/{id}")
    public ResponseEntity updatePost(@PathVariable Long id, @RequestBody Post postDetails) {
        Post post = postRepository.findById(id)
                .orElseThrow(() -> new ResourceNotFoundException("Post not found with id " + id));
        
        post.setTitle(postDetails.getTitle());
        post.setContent(postDetails.getContent());
        Post updatedPost = postRepository.save(post);
        return ResponseEntity.ok(updatedPost);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity deletePost(@PathVariable Long id) {
        Post post = postRepository.findById(id)
                .orElseThrow(() -> new ResourceNotFoundException("Post not found with id " + id));
        
        postRepository.delete(post);
        return ResponseEntity.noContent().build();
    }
}

3.2 Creating Repository

Create a repository to access the database using Spring Data JPA:

package com.example.blog.repository;

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

public interface PostRepository extends JpaRepository {
}

4. Authentication and Authorization

4.1 Configuring Spring Security

To add basic authentication features to the blog application, configure Spring Security. Create the WebSecurityConfig class and set it up as follows:

package com.example.blog.config;

import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
            .authorizeRequests()
            .antMatchers("/api/posts/**").authenticated()
            .and()
            .httpBasic();
    }
    
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

5. Client Integration

Integrate the backend API with the client application to complete the blog application. You can use various frontend frameworks such as React, Vue, Angular to communicate with the API and exchange data. Here is an example of calling the backend API from the frontend using Axios:

import axios from 'axios';

const API_URL = 'http://localhost:8080/api/posts';

export const fetchPosts = async () => {
    const response = await axios.get(API_URL, {
        auth: {
            username: 'user',
            password: 'password'
        }
    });
    return response.data;
};

// Implement other CRUD functions

6. Conclusion

In this course, we covered the process of creating a basic blog application using Spring Boot. We addressed various topics from project preparation, database configuration, RESTful API implementation, authentication and authorization, to client integration. We hope you gain experience to create your own blog using various technologies.

Additionally, it is recommended to utilize various materials and communities related to Spring Boot to gain more knowledge and improve your skills. We hope this course serves as your first step in Spring Boot development!

Spring Boot Backend Development Course, Blog Production Example, Writing Controller Method Code

Hello! In this course, we will learn how to create a blog using Spring Boot and explore in-depth how to write controller methods. Spring Boot is a Java-based framework that helps you easily develop web applications. In this course, we will implement basic blog functions and aim to build a RESTful API.

1. Introduction to Spring Boot

Spring Boot is an extension of the Spring framework that makes it easier to set up and run Spring applications. The main goal is to reduce complex Spring configurations and help you start applications quickly.

1.1. Advantages of Spring Boot

  • Quick Start: Embedded server allows you to run applications in a short time
  • Auto Configuration: Automatically sets up various libraries and frameworks
  • Flexible Configuration: Easily manage application settings through configuration files

2. Setting Up the Development Environment

Before starting the blog project, let’s set up the necessary development environment. Below are the essential components you need to install for Spring Boot.

  • Java Development Kit (JDK): Install JDK 8 or higher.
  • IDE: Install an IDE such as IntelliJ IDEA, Eclipse, or VSCode
  • Build Tool: Use Maven or Gradle for dependency management

2.1. Creating a New Spring Boot Project

You can create a new Spring Boot project using Spring Initializr. Follow the steps below:

  1. Visit the Website: Go to Spring Initializr.
  2. Enter Project Metadata: Fill in the Group, Artifact, and Name fields, and select Web, JPA, and H2 Database in Dependencies.
  3. Create the Project: Click the Generate button to download the project and open it in your IDE.

3. Designing the Blog Model

Let’s design the basic data model for the blog. Our blog will have the following Entity class.

3.1. Post Entity

package com.example.blog.model;

import lombok.Data;

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

@Entity
@Data
@Table(name = "posts")
public class Post {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String title;
    private String content;
    private LocalDateTime createdAt;
    private LocalDateTime updatedAt;
}

The code above describes the Post class that represents a blog post. It connects to the database using JPA and automatically generates getter, setter, and toString methods through Lombok’s @Data annotation.

3.2. Creating the Repository

You need to create a Repository interface for interacting with the database. You can easily implement it using Spring Data JPA.

package com.example.blog.repository;

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

@Repository
public interface PostRepository extends JpaRepository {
}

4. Implementing the Controller

Now, let’s implement a controller that provides a RESTful API for managing blog posts. The controller handles web requests and manages the connection between the service layer and the database.

4.1. Writing the PostController Class

package com.example.blog.controller;

import com.example.blog.model.Post;
import com.example.blog.repository.PostRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/posts")
public class PostController {
    private final PostRepository postRepository;

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

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

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

The code above defines two endpoints for creating and retrieving blog posts. @GetMapping retrieves all posts, while @PostMapping creates a new post.

4.2. Handling Requests and Responses

It is essential to handle requests sent from clients and generate appropriate responses. You can notify the client of the request processing result by returning a response along with the HTTP status code.

 @PostMapping
    public ResponseEntity createPost(@RequestBody Post post) {
        Post createdPost = postRepository.save(post);
        return ResponseEntity.status(HttpStatus.CREATED).body(createdPost);
    }

5. Adding the Service Layer

By adding a service layer that handles business logic, you can improve code separation. Splitting the interaction logic with the database into the service layer makes testing and maintenance easier.

5.1. Implementing the PostService Class

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 getAllPosts() {
        return postRepository.findAll();
    }

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

5.2. Using the Service Layer in the Controller

Modify the controller to call the service layer to perform the logic.

 @Autowired
    private PostService postService;

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

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

6. Exception Handling

Let’s also discuss how to handle various exceptions that may occur in the API. You can implement an exception handler to ensure consistent responses.

6.1. Writing the GlobalExceptionHandler Class

package com.example.blog.exception;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public ResponseEntity handleException(Exception e) {
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
    }
}

7. Testing the API

Finally, you can test the API using Postman or cURL. Below is an example using Postman.

7.1. Retrieve All Posts

GET http://localhost:8080/api/posts

7.2. Create a New Post

Send JSON format data to http://localhost:8080/api/posts

{
        "title": "First Blog Post",
        "content": "Hello, this is the first blog post."
    }

8. Conclusion and Future Improvements

We have looked at the basics of developing a blog backend using Spring Boot. You should now understand the essential elements needed to create a RESTful API, including writing controller methods, exception handling, and adding a service layer.

Future improvements could include adding authentication and authorization, file uploads, comments functionality, and writing test code to further enhance the blog features. If you have laid the foundation through this course, challenge yourself with more complex projects! We support your development journey.

References