Spring Boot Backend Development Course, Server and Client

Hello! In this course, we will learn in detail about backend development using Spring Boot. We will understand the interaction between server and client, and create a real application. This course is designed to be useful for everyone from beginners to intermediate learners.

1. What is Spring Boot?

Spring Boot is an application framework based on the Spring framework that helps you quickly create Spring applications without complex configuration. Spring Boot has the following features:

  • Minimal Configuration: It minimizes configuration through automatic setting features.
  • Standalone: It can run as a standalone application using embedded Tomcat, Jetty, or Undertow.
  • Starter Packages: It provides pre-configured starter packages for commonly used libraries.
  • Enhanced Productivity: It offers various features to allow developers to write code more quickly and easily.

2. Concepts of Server and Client

Server and client are the basic units of data communication in a network. The client is responsible for requesting services, while the server responds to the client’s requests. This can be explained in more detail as follows:

  • Client: Provides an interface that users interact with directly, such as a web browser or mobile app. The client sends HTTP requests to the server and receives HTTP responses from the server.
  • Server: A program that processes requests from clients. The server interacts with the database to return results for client requests.

3. Installing Spring Boot

To use Spring Boot, you need JDK, Spring Boot, and an IDE as the development environment. You can install it following these steps:

  1. Install Java Development Kit (JDK): Install JDK 11 or higher. You can use Oracle JDK or OpenJDK.
  2. Install IDE: Install an IDE like IntelliJ IDEA, Eclipse, or Spring Tool Suite (STS).
  3. Install Spring Boot CLI (optional): You can install Spring Boot CLI to create Spring Boot projects from the command line.

4. Creating a Spring Boot Project

You can create a Spring Boot project in several ways. The most convenient way is to use Spring Initializr. Let’s follow these steps to create a project:

  1. Access Spring Initializr: Go to start.spring.io .
  2. Set Project Configuration: Set the project metadata. Choose Maven Project, Java, and the appropriate Spring Boot version.
  3. Add Dependencies: Add the necessary dependencies such as Spring Web, JPA, H2 Database, etc.
  4. Download Project: Click the Generate button to download the project.

5. Creating a Simple RESTful API

Now, we will create a simple RESTful API using Spring Boot. Here, we will implement an API to manage ‘Books’ as resources.

5.1 Creating a Domain Model

First, we define the ‘Book’ domain model. The properties of the book will include ID, title, author, and publication year.

package com.example.demo.model;

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

@Entity
public class Book {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    
    private String title;
    private String author;
    private int year;

    // Getters and setters omitted
}
            

5.2 Creating a Repository Interface

Create a repository interface to interact with the database using JPA.

package com.example.demo.repository;

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

public interface BookRepository extends JpaRepository<Book, Long> {
}

            

5.3 Creating a Service Class

Create a service class for business logic processing. This class can add and retrieve book data using the repository.

package com.example.demo.service;

import com.example.demo.model.Book;
import com.example.demo.repository.BookRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BookService {
    @Autowired
    private BookRepository bookRepository;

    public List<Book> getAllBooks() {
        return bookRepository.findAll();
    }

    public Book addBook(Book book) {
        return bookRepository.save(book);
    }
}
            

5.4 Creating a Controller Class

Create a REST controller to handle client requests. This controller can define the API endpoints.

package com.example.demo.controller;

import com.example.demo.model.Book;
import com.example.demo.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/books")
public class BookController {
    @Autowired
    private BookService bookService;

    @GetMapping
    public List<Book> getAllBooks() {
        return bookService.getAllBooks();
    }

    @PostMapping
    public Book addBook(@RequestBody Book book) {
        return bookService.addBook(book);
    }
}
            

5.5 Running the Application

Now that all settings are complete, start the application by running the DemoApplication class’s main method.

6. Testing the API with Postman

We will test whether the API we created works correctly using Postman. Follow these steps:

  1. Run Postman: Open the Postman application and create a new request.
  2. Send GET Request: Enter http://localhost:8080/api/books in the URL and send a GET request. The current book list should appear as a response.
  3. Send POST Request: To add a new book, enter http://localhost:8080/api/books in the URL and set up a POST request. Set the Body to JSON format and enter the book information.

7. Connecting to Database

In this section, we will learn how to connect Spring Boot with the H2 database. H2 database is an in-memory database suitable for testing and development.

7.1 Database Configuration

Add H2 database settings in the application.properties file of the Spring Boot application:

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

7.2 Data Initialization

To add initial data when the application runs, you can use a data.sql file to set up the initial data.

INSERT INTO book (title, author, year) VALUES ('Effective Java', 'Joshua Bloch', 2020);
INSERT INTO book (title, author, year) VALUES ('Spring in Action', 'Craig Walls', 2018);
            

8. Exception Handling

We will learn how to handle exceptions that may occur in the generated API. Spring allows global exception handling using @ControllerAdvice.

package com.example.demo.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<String> handleException(Exception e) {
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
    }
}
            

With this setup, all exceptions will be handled, and an appropriate response will be returned to the client.

9. Communication with Client

In this section, we will learn about the methods of communication between the client and server. Generally, clients interact with servers via REST APIs. The common request methods are as follows:

  • GET: Data retrieval
  • POST: Data creation
  • PUT: Data modification
  • DELETE: Data deletion

10. Implementing Client Application

Having successfully implemented the API on the server side, let’s create a client application. Here, we will create a simple HTML and JavaScript-based frontend to communicate with the REST API.

10.1 Creating HTML Structure

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Book List</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <h1>Book List</h1>
    <table id="bookTable">
        <tr><th>Title</th><th>Author</th><th>Year</th></tr>
    </table>
    <script>
        function fetchBooks() {
            $.get("http://localhost:8080/api/books", function(data) {
                data.forEach(function(book) {
                    $('#bookTable').append(`<tr><td>${book.title}</td><td>${book.author}</td><td>${book.year}</td></tr>`);
                });
            });
        }
        $(document).ready(function() {
            fetchBooks();
        });
    </script>
</body>
</html>
            

11. Security

Security is very important in applications. You can implement authentication and authorization through Spring Security. Here’s a simple example of security settings:

package com.example.demo.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;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
            .authorizeRequests()
            .anyRequest().authenticated()
            .and()
            .httpBasic();
    }
}
            

Conclusion

Through this course, you learned about backend development using Spring Boot and the principles of communication between server and client. I encourage you to gain experience by developing real applications in various scenarios. I hope you continue to acquire more knowledge and keep learning. Thank you!