Home » Java » Enterprise Java » Spring MVC Annotations

About Shubhra Srivastava

Shubhra Srivastava
Shubhra is a software professional and founder of ProgrammerGirl. She has a great experience with Java/J2EE technologies and frameworks. She loves the amalgam of programming and coffee :)

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.

Published on Java Code Geeks with permission by Shubhra Srivastava, partner at our JCG program. See the original article here: Spring MVC Annotations

Opinions expressed by Java Code Geeks contributors are their own.

(0 rating, 0 votes)
You need to be a registered member to rate this.
Start the discussion Views Tweet it!
Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy

Leave a Reply

avatar

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

  Subscribe  
Notify of