Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Spring MVC | Spring Boot Basics
Spring Boot Backend
course content

Зміст курсу

Spring Boot Backend

Spring Boot Backend

1. Backend Development Basics
2. Spring Boot Basics
3. RESTful API
4. Working with Databases
5. Testing Backend Applications

bookSpring MVC

Why You Need Spring MVC

Spring MVC helps organize a web application by following the principle of separation of concerns, making it easier to develop, test, and maintain code. It provides a framework for creating web pages and handling user requests, as well as for integrating with business logic and databases.

In our application, we utilize a three-tier architecture to separate the logic into distinct modules. We have the repository, service, and controller layers. This separation makes it easier to maintain and test the application.

Key Annotations and Their Role

For each layer, we have specific annotations, which are essential for Spring to automatically recognize and register components in the application context (we’ll discuss what this means later). This helps maintain a cleaner architecture and improves code readability.

Repository Layer Annotation

The @Repository annotation is used to indicate a class that interacts with the database. These classes typically contain methods for performing CRUD operations (Create, Read, Update, Delete).

java

UserRepository

copy
1234567
@Repository public class UserRepository { // Method to find a user by their ID public User findById(Long id) { // Logic to retrieve the user from the database } }

In this example, UserRepository is marked as a repository, allowing Spring to handle data access-related exceptions and automatically integrate it into the application.

Service Layer Annotation

The @Service annotation is used to designate a class as a component of the business logic. These classes contain methods that implement the application's business rules and operations.

java

UserService

copy
1234567
@Service public class UserService { // Method to retrieve a user by their ID public User getUserById(Long id) { // Logic to get the user by ID } }

The @Service annotation indicates that this class contains the application's business logic, making it easy to use in other parts of the application. This simplifies development since you don’t have to manually create instances of this class — Spring handles that for you.

Controller Layer Annotation

Since the controller layer serves as the interaction point between the client and our application, we need to establish endpoints for clients to access it. This involves associating specific URLs with each method, enabling clients to interact with those methods directly.

To achieve this, we need to annotate the class as a @Controller and define a method that will act as the request handler.

java

Main

copy
12345678
@Controller public class HomeController { @RequestMapping(value = "/", method = RequestMethod.GET) public String home() { // code } }

The @RequestMapping annotation is used to link HTTP requests to specific methods in the controller. It helps specify which URL patterns and types of requests (like GET or POST) a method should respond to. For instance, in this case, the home() method will respond to GET requests made to the root URL.

When a user visits example.com/, their browser sends an HTTP GET request to the server, which reaches the Spring application. The Spring framework finds the matching @RequestMapping in the HomeController, calls the home() method to handle the request, and then sends back the appropriate response to the user's browser.

There are annotations that provide more precise mapping for the type of request method, such as @GetMapping, @PostMapping, @DeleteMapping, and so on. In their attributes, you simply specify the URL that can be used to access them.

java

Main

copy
12345678
@Controller public class HomeController { @GetMapping("/home") public String home() { // code } }

In this example, if we access the URL /home, we will be directed to the home() method ONLY if it was a GET request. If a different type of request method is used, the server will respond with a 404 Not Found error for that URL.

@RequestParam

What are URL request parameters? These are the parameters that appear after the question mark in the URL. For example, if we have the address -> example.com/home?name=Alex (key = name, value = Alex), we can directly retrieve the parameter (name) in the welcomeUser() method.

java

Main

copy
12345678
@Controller public class WelcomeController { @GetMapping("/home") public String welcomeUser(@RequestParam(name = "name") String name) { // code } }

Here, the parameter name is extracted from the URL (/home?name=Alex) and passed to the welcomeUser() method.

You can also extract more than one parameter, not just a single one. All parameters in the URL should be separated by the & symbol. For example: example.com/home?name=Alex&age=20.

java

Main

copy
12345
@GetMapping("/home") public String getUserInfo(@RequestParam String name, @RequestParam int age) { // Logic to handle the request using 'name' and 'age' parameters return "User Name: " + name + ", Age: " + age; }

In this example, the endpoint /home can be accessed with a URL like example.com/home?name=Alex&age=20, where name and age are the parameters passed to the method.

@PathVariable

In Spring MVC, the @PathVariable annotation is used to bind a variable in the URL directly to a method parameter. It allows you to capture dynamic values from the URL and use them within the method.

If you need to dynamically set a URL, meaning you pass a value directly within the URL itself, you can use the @PathVariable annotation.

For example, if you have a URL pattern like /users/{id}, you can use @PathVariable to access the {id} part of the URL and pass it as a parameter to your method.

java

Main

copy
12345678
@Controller public class UserController { @GetMapping("/user/{id}") public String getUser(@PathVariable("id") Long userId) { // code } }

In this example, id is extracted from the URL (/user/123) and passed to the getUser() method, where the value 123 is assigned to the userId parameter.

These annotations help developers easily configure HTTP request handling, bind data to objects, and manage responses, enhancing code readability and maintainability.

Summary

Spring MVC simplifies web application development by separating request handling, application logic, and view rendering. Controllers, marked with the @Controller or @RestController annotation, handle requests and return data for display.

1. What does the `@Controller` annotation do in Spring MVC?
2. Which annotation method is used to handle `GET requests` in Spring MVC?
What does the `@Controller` annotation do in Spring MVC?

What does the @Controller annotation do in Spring MVC?

Виберіть правильну відповідь

Which annotation method is used to handle `GET requests` in Spring MVC?

Which annotation method is used to handle GET requests in Spring MVC?

Виберіть правильну відповідь

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 2. Розділ 3
some-alt