Spring MVC Annotations

Read other articles of the series :

 

In this article, we will explore and discuss Spring MVC annotations. Annotations brought major changes in programming style and slowly eliminating the XML based configurations. Spring Framework has started using the annotations from the release of Spring 2.5.

 

1. @Controller Annotation

This annotation serves as a specialization of @Component, allowing for implementation classes autodetected through classpath scanning.@Controller annotation tells the Spring IOC container to treat this class as Spring MVC controller.

In order to configure/ customize MVC components, Spring MVC provides an option to handle it either through Java Config or XML. Add @EnableWebMvc will import the Spring MVC configuration from.WebMvcConfigurationSupport For XML based configuration use the 

<context:component-scan base-package="com.javadevjournal">
@Controller
public class SpringMVCController {

 //HTTP Mappings
}

 

2. @RestController Annotation

A convenience annotation that is itself annotated with @Controller and @ResponseBody.

@RestController
public class FilterExampleController {

 @GetMapping
 public String greeting() {
  return "Hello World";
 }

 @GetMapping(value = "/greeting")
 public String customGreetings() {
  return "Hello From Custom Greetings";
 }
}

 

3. @RequestMapping

Annotation for mapping web requests methods in the Spring MVC Controller. Both Spring MVC and Spring WebFlux support this annotation.@RequestMapping annotation provides a number of options to customize its behavior.

  • Consumes – The consumable media types of the mapped request, narrowing the primary mapping. (e.g. @RequestMapping(consumes = {"application/json", "application/xml"})).
  • method – The HTTP request methods to map (e.g. method = {RequestMethod.GET,RequestMethod.POST}).
  • header – The headers of the mapped request.
  • name – the name of the mapping.
  • value – The primary mapping expressed by this annotation
  • produces – The producible media types of the mapped request.

Here is an example for the @RequestMapping

@Controller
public class SpringMVCController {

 @RequestMapping(value = {
  "/greetings",
  "/hello-world"}, method = {RequestMethod.GET,RequestMethod.POST}, 
   consumes = {"application/json","application/xml"}, 
   produces = { "application/json"},headers = {"application/json"
  })
 public String hellpWorld() {
  return "Hello";
 }
}

This annotation can be used both at the class and at the method level

@Controller
@RequestMapping(value = {
 "/greetings"
}, method = {
 RequestMethod.GET
})
public class SpringMVCController {}

If you are using Spring 4.3+, check out new and improved @RequestMapping annotations.

 

4. @RequestParam

Annotation which indicates that a method parameter is bound to a web request parameter. Request parameters passed by the browser/client as part of the HTTP request, the @RequestParam annotation help to map these parameters easily at the controller level.

@GetMapping("/request-mapping-example")
public String requestMappingExample(@RequestParam("code") String code) {
 //
}

With @RequestParam we can specify default value when Spring finds no or empty value in the request.

public String requestMappingExample(@RequestParam(defaultValue = "1") long productQty){}

 

5. @PathVariable

This annotation indicates that a method parameter bound to a URI template variable. We specify the variable as part of the @RequestMapping and bind a method argument with @PathVariable. Let’s take an example where we want to pass productCode as part of the URI and not request parameter.

@GetMapping("/products/{id}")
public String getProduct(@PathVariable("id") String id) {
 //
}

Please note following extra points while using @PathVariable.

  • The variable name in the @PathVariable annotation is optional if the name of the part in the template matches the name of the method argument. For the above example, we can omit “id” from the @PathVariable annotation.
    @GetMapping("/products/{id}")
    public String getProduct(@PathVariable String id) {
     //
    }
  • Use “require” parameter to mark the path variable as an optional.
    @GetMapping("/products/{id}")
    public String getProduct(@PathVariable(required = false) String id) {
     //
    }

    In this case, id is an optional field

 

6. @SessionAttribute

Annotation to bind a method parameter to a session attribute.@SessionAttribute used to pass value across different requests through the session. Rather than using HttpSession object directly, using this annotation can benefit auto type conversion and optional/required check.

@GetMapping("/user")
public String sessionexample(@SessionAttribute(name = "userLoginTime") LocalDateTime startDateTime) {
 //
}

 

7. @RequestBody

Annotation indicating a method parameter bound to the body of the web request. The body of the request is passed through an HttpMessageConverter to resolve the method argument depending on the content type of the request.

@PostMapping("/product/save") public String saveProduct(@RequestBody Product product){}

 

8. @ResponseBody

Annotation that indicates a method return value bound to the web response body. Supported for annotated handler methods. Spring treats the result of the method as the response itself.

 @GetMapping("/products/{id}")
 public @ResponseBody Product saveProduct(@PathVariable("id") String id) {
  //
 }

 

9. @ExceptionHandler

ExceptionHandler is a Spring annotation handle exceptions thrown by request handling. This annotation works at the @Controller level.

@GetMapping("/greeting")
String greeting() throws Exception {
 //
}

@ExceptionHandler({
 Exception.class
})
public handleException() {
 //
}

 

10. @InitBinder

Annotation that identifies methods which initialize the WebDataBinder and used for populating command and form object arguments of annotated handler methods.

@InitBinder
protected void initBinder(WebDataBinder binder) {

 binder.setValidator(customValidator);

}

 

11. @ModelAttribute

@ModelAttribute refers to a property of the Model object in Spring MVC. This annotation binds a method parameter or method return value to a named model attribute, exposed to a web view.

@PostMapping("/customer-registration")
public String processForm(@ModelAttribute("customer") Customer customer) {}

On the other hand, the annotation is used to define objects which should be part of a Model. So if you want to have a Customer object referenced in the Model you can use the following method:

@ModelAttribute("customer")
public Person getCustomer() {
 //
}

we don’t have to specify the model key, Spring uses the method’s name by default

@ModelAttribute
public Person getCustomer() {
 //
}

 

Summary

In this article, we covered Spring MVC annotations for handling HTTP request and response in a web application.

Umesh

Hello!! I am Umesh- an engineer by profession and a photographer by passion.I like to build stuff on the web using OSS and love to capture the world through my lens.

follow me on:

Leave a Reply

avatar

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  Subscribe  
Notify of