Most Popular Spring MVC Annotations

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.

Popular Annotations

@Controller

The @Controller annotation is a class-level annotation used to designate a particular class as a controller within the Spring framework.

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"
 }
    
}

@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"
    }
}

@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:

  1. value or path: Specify the URL path or paths that the controller method will handle.
  2. method: Define the HTTP request method(s) that the handler method can handle (e.g., GET, POST, PUT, DELETE).
  3. params: Define parameters that must be present in the request for the handler method to be invoked.
  4. headers: Specify the headers that must be present in the request for the handler method to be invoked.
  5. consumes: Specify the media types that the handler method can consume.
  6. produces: Specify the media types that the handler method can produce.

@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
}

@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 + "!";
    }
}

@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
    }
}

@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!";
    }
}

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!

Leave a Reply

Your email address will not be published. Required fields are marked *

Join the Tribe