1. Introduction
One of the standout features of Spring MVC is its extensive utilization of annotations, which play a crucial role in simplifying the development process. Annotations enable developers to declaratively define the configuration and behavior of their application components.
In this article, we will delve into some of the most popular annotations in Spring MVC and demonstrate how they are employed to define controllers, manage requests, bind data, and perform other tasks.
2. Popular Annotations
2.1. @Controller
The @Controller
annotation is a class-level annotation used to designate a particular class as a controller within the Spring framework.
In the context of Spring MVC, a controller is a specialized class responsible for handling user requests. Each controller class contains methods, often referred to as endpoints, which are mapped to specific URLs. For example, a method in a controller class might handle requests for /users
or /home
.
Behind the scenes, Spring MVC utilizes a handler mapping mechanism to establish the relationship between these URL patterns and the corresponding handler methods in controller classes. When the application starts up, the handler mapping component (such as RequestMappingHandlerMapping
) scans the application for classes annotated with @Controller
then the class methods are annotated with @RequestMapping
. It extracts the URL patterns specified in this annotation and associates them with the corresponding handler methods. This mapping is then used by the DispatcherServlet
to route incoming requests to the appropriate handler methods based on their URL patterns.
When using @Controller
, the general convention is for the methods to return the name of the view we intend to render and return to the user. However, this behavior can be customized by utilizing @ResponseBody
and @RestController
annotations, as discussed in the following section of this blog post.
Example:
@Controller
public class MyController {
@RequestMapping(value="/home")
public Strng home() {
return "home"
}
}
2.2. @ResponseBody
The @ResponseBody
annotation indicates that the return value of the method should be serialized directly to the HTTP response body. It is used to return data rather than a view name.
when using @ResponseBody the HandlerAdpater will directly put the data (JSON, XML, string ) to the HTTP response and set null to the returned ModelAndView Object.
@Controller
public class MyController {
@GetMapping("/user")
@ResponseBody
public String getUserEmail() {
return "hamza@javalaunchpad.com"
}
}
2.3. @RequestMapping
The @RequestMapping
annotation is used to map web requests onto specific handler classes and/or handler methods. It is used to define the URL patterns for which the controller should be invoked.
Example:
@Controller
public class MyController {
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String hello() {
return "helloPage";
}
}
The @RequestMapping
annotation in Spring MVC is quite versatile and offers various attributes that can be used to customize the mapping of HTTP requests to handler methods. Here are some of the common attributes:
value
orpath
: Specify the URL path or paths that the controller method will handle.method
: Define the HTTP request method(s) that the handler method can handle (e.g., GET, POST, PUT, DELETE).params
: Define parameters that must be present in the request for the handler method to be invoked.headers
: Specify the headers that must be present in the request for the handler method to be invoked.consumes
: Specify the media types that the handler method can consume.produces
: Specify the media types that the handler method can produce.
2.4. @RequestMapping shortcuts
These annotations are specialized versions of @RequestMapping
that narrow down the mapping to specific HTTP methods (GET, POST, PUT, DELETE) respectively. They serve as shortcuts for declaring @RequestMapping
with the respective method already set.
- @GetMapping: Handles HTTP GET requests.
- @PostMapping: Handles HTTP POST requests.
- @PutMapping: Handles HTTP PUT requests.
- @DeleteMapping: Handles HTTP DELETE requests.
- @PatchMapping: Handles HTTP PATCH requests.
For example, instead of using @RequestMapping(value = "/hello", method = RequestMethod.GET)
, we can simply use @GetMapping("/hello")
.
@Controller
public class MyController {
@GetMapping("/hello")
public String hello() {
return "helloPage";
}
}
Internally, these shortcuts are indeed mapped to @RequestMapping
with the appropriate HTTP method already specified. here is an example of @GetMapping.
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@RequestMapping(
method = {RequestMethod.GET}
)
public @interface GetMapping {
}
Note: In Practice, we use @RequestMapping
at the class level to specify URL patterns that are common to all handler methods within that class. This is useful when we want to group related request mappings together.
@Controller
@RequestMapping("/products")
public class ProductController {
@GetMapping("/list")
public String listProducts() { // this method is mapped to /products/list
return "productList";
}
@GetMapping("/detail")
public String getProductDetail() {
return "productDetail";
}RequestMapping
}
2.5. @RequestParam
The @RequestParam
annotation is used to extract request parameters from the URL query string. It binds the parameter values from the request to the method parameters in the controller.
Example:
@Controller
public class TestController {
@GetMapping("/greet")
@ResponseBody
public String greet(@RequestParam("name") String name) {
return "Hello, " + name + "!";
}
}
![](https://javalaunchpad.com/wp-content/uploads/2024/03/Screenshot-from-2024-03-14-23-39-00.png)
2.6. @PathVariable
The @PathVariable
annotation is used to extract values from the URI template and bind them to method parameters.
Example:
@Controller
public class MyController {
@GetMapping("/user/{id}")
public User getUser(@PathVariable Long id) {
// Logic to fetch user with given id
}
}
2.7. @RestController
The @RestController
annotation is a specialized version of @Controller
which combines @Controller
and @ResponseBody
. It is used to define RESTful web services.
Example:
@RestController
public class MyRestController {
@GetMapping("/hello")
public String hello() {
return "Hello, World!";
}
}
3. Conclusion
In this article, we’ve explored some of the most popular Spring MVC annotations that will be essential throughout our Spring MVC tutorial series.
Happy Coding!