Spring

Spring MVC Annotations

Introduction:

Spring 2.5 onwards, we can use annotations to mark our Spring components.

One way of doing so is to use a <component-scan> tag in our appConfig.xml:

<context:component-scan base-package="com.programmergirl" />

The Spring container will then recursively scan all components in the given package & its sub-packages.

In this quick tutorial, we’ll discuss the most commonly used Spring MVC annotations.

Defining a Controller:

There’re two different annotations we can use for our controller based on its type:

1. @Controller:

We can simply use this annotation to mark any of our Spring MVC controller classes:

@Controller
public class MyController {

   ...
}

2. @RestController:

This annotation is useful for annotating our RESTful controllers:

@RestController
public class MyRestController {
    ...
}

This annotation is itself annotated with both @Controller and @ResponseBody annotations.

We have covered the difference between @Controller and @RestController in much detail in one of our other articles.

Request-Handling Annotations:

Let’s now look at the annotation we can use for handling our HTTP requests:

1. @RequestMapping:

We use this annotation to map the web request methods in the Spring MVC Controller. We can also customize it using its available attributes:

  • method: denotes one the HTTP request methods – PUT, GET, POST, DELETE, PATCH
  • value: the mapped URL
  • params: filters the request based on the HTTP parameters
  • headers: filters the request based on the HTTP headers.
  • produces: defines the media type of the HTTP responses
  • consumes: specifies the media type of the HTTP request

@Controller
@RequestMapping("/hello-world")
class MyController {
 
    @RequestMapping(value = "/message", method = RequestMethod.GET)
    String message() {
        return "Hello World!";
    }
}

We can also use this annotation at class-level for setting up some common properties.

Moreover, Spring 4.3 onwards, @RequestMapping offers several variants for different HTTP methods. These include @GetMapping, @PutMapping, @PostMapping, @DeleteMapping, and @PatchMatching.

2. @RequestParam:

With this annotation, we can bind an HTTP request parameter to the method parameter:

@GetMapping("/message")
String message(@RequestParam("userName") String userName) {
    return "Hello " + userName;
}

Optionally, we can also provide a default value. For the missing value of the request parameter, the default value is used:
@GetMapping("/message")
String message(@RequestParam(defaultValue = "Sam") String userName) {
    return "Hello " + userName;
}

3. @PathVariable:

We can bind the method parameter to one of the variables in the path or URI. We’ll use @PathVariable for it:

@GetMapping("/message/{userName}")
String message(@PathVariable String userName) {
    ...
}

Also, we can choose to mark a path variable as optional by setting required to false:
@GetMapping("/message/{userName}")
String message(@PathVariable(required = false) String userName) {
    ...
}

4. @RequestBody:

An HTTP request body can be passed as an argument to a handler method in our controller.  We often use it for reading the request body of requests with HTTP methods as PUT and POST.

@PostMapping("/message")
String message(@RequestBody String userName) {
    ...
}

The content is automatically deserialized using HttpMessageConverter based on its type.

Response-Handling Annotations:

Now, let’s explore some annotations we can use for dealing with HTTP responses:

1. @ResponseBody:

Similar to the @RequestBody, we have a @ResponseBody annotation. When we annotate a method with this annotation, Spring treats the result of this method as the response itself:

@GetMapping("/message")
@ResponseBody
String message() {
    return "Hello World!!";
}

We can also annotate our @Controller class with this annotation. If so, all methods in our controller will use it.

2. @ResponseStatus:

With this, we can map the desired HTTP response status to the methods in our controller:

@ExceptionHandler(UserAccessDeniedException.class)
@ResponseStatus(HttpStatus.FORBIDDEN)
void onUserAccessDeniedException(UserAccessDeniedException exception) {
    ...
}

We can learn more about how to set a status code and reason using @ResponseStatus.

3. @ExceptionHandler:

We can write custom exception handler methods. These methods will be invoked when an exception of its type is raised during the method execution:

@ExceptionHandler(UserAccessDeniedException.class)
void onUserAccessDeniedException(UserAccessDeniedException exception) {
    // ...
}

Conclusion:

In this tutorial, we skimmed through most of the commonly used Spring MVC annotations.

3 comments
Pingback: Spring MVC Annotations | Good day Android - Android World

Leave a Comment

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