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 used the annotations from the release of Spring 2.5.
[thrive_toggles_group”][thrive_toggles title=”Read other articles of the series :” no=”1/1″]
- Spring Framework Annotations
- Spring Boot Annotations
- Spring MVC Annotations [Current Article]
[/thrive_toggles][/thrive_toggles_group]
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.
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 several 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";
}
}
[pullquote align=”normal”]This annotation can be used both at the class and at the method level [/pullquote]
@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 shows that it binds a method parameter 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 shows 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) { // }
Here, 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
The @RequestBody annotation showing a method parameter bound to the body of the web request. It passes the body of the request through an HttpMessageConverter
to resolve the method argument depending on the content the request.
@PostMapping("/product/save") public String saveProduct(@RequestBody Product product){}
8. @ResponseBody
The @ResponseBody Annotation that shows 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 ModelAttribute 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) {}
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() {
//
}
12. @Qualifier Annotation
The @Qualifier annotation helps disambiguate bean references when Spring otherwise could not do so. In our case, to we can use the @Qualifier annotation help in the issue to choose the correct bean for the dependency injection. Let’s change our previous example:
public class OrderFacade {
@Qualifier("userServiceImpl")
@Autowired
private UserService userService;
}
For more details please read @Qualifier Annotation
13. @CrossOrigin
This annotation allows the cross-domain communication for the annotated handler methods. This @CrossOrigin
annotation enables cross-origin resource sharing only for this specific method. Let’s take an example where we want to allow only <a class="bare" href="http://localhost:9000">http://localhost:9002</a>
to send cross-origin requests.
@CrossOrigin(origins = "http://localhost:9002")
@GetMapping("/hello")
public String greeting(@RequestParam(required = false, defaultValue = "Stranger") String name) {
return "Hello" + name;
}
For more details read Spring Boot CORS.
Summary
In this article, we covered Spring MVC annotations for handling HTTP request and response in a web application.
Comments are closed.