Contenido del Curso
Spring Boot Backend
Spring Boot Backend
Spring 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).
UserRepository
@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.
UserService
@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.
Main
@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.
Main
@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.
Main
@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
.
Main
@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.
Main
@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.
¡Gracias por tus comentarios!