Spring Mvc Annotations

By | | Updated : 2021-07-27 | Viewed : 100 times

Spring Mvc Annotations

In this quick tutorial, we will explore the most important annotations with Spring MVC. Let\'s get started to learn.

@Controller

In Spring MVC web requests should be handled by the controllers. So to write the handler classes we need to use the @Controller annotation. Please see the below given example for the @Controller annotation. @Controller

@Controller example
@Controller
@RequestMapping("/products")
public class ProdController {

@Autowired ProdService prodService;

 @RequestMapping(value = "/list", produces = {"application/JSON"})
 @ResponseBody
 List getProdcts(){
 	return prodService.getPrducts();
 }

}

@Controller vs @RestController

Both are mostly equal to the @Component which is used for mapping web requests. These are get scanned within the ClassPath automatically. @RestController is equal to @Controller and @Responsebody. And with @Controller it has to send a response to the View by taking the help of ViewResolver, unlike @RestController.

@RequestMapping

In the implementation of handler classes, we need to map web requests to methods in controller classes. So it is required to use the @RequestMapping annotation. Please notice below the given example for @RequestMapping in Spring MVC.

@RequestMapping example
@RestController
@RequestMapping("/products")
public class ProdController {
@Autowired ProdService prodService;

	 @RequestMapping(value = "/list", produces = {"application/JSON"})
	 @ResponseBody
	 List getProdcts(){
	 	return prodService.getPrducts();
	 }
}

@PathVariable

@PathVariable will be used to send the data as variables in the request URI. For instance, we /product/1001 here we send the data product id as 1001. So the same value can be obtained with @Pathvariable. See below given example.

@PathVariable example
@RestController
@RequestMapping("/products")
public class ProdController {

 @Autowired ProdService prodService;
 @RequestMapping(value = "product/{productId}", produces = {"application/JSON"})
 @ResponseBody
 Product getProdcts(@PathVariable("id") String productId){
	 return ProdService.getProduct(id);
 }

}

@RequestParam

You might aware of request params in the Servlet. So the same concept can be achieved by the @RequestParam in Spring MVC. Notice below given example for @RequestParam

@RestController @RequestMapping("/products") public class ProdController { @Autowired ProdService prodService; @RequestMapping(value = "product", produces = {"application/JSON"}) @ResponseBody Product getProdcts(@RequestParam String id){ return ProdService.getProduct(id); } }

@RequestBody

For accessing the body of the HTTP request @RequestBody is used. Let's see an example of @RequestBody in the Spring.

@RequestBody example
@Controller
@RequestMapping("/products")
public class ProdController {

	@Autowired ProdService prodService;
	@ResponseBody @RequestMapping("/save")
	public Description saveProducts(@RequestBody Products products){
	    return prodService.saveProducts(products);
	}
}



@ResponseBody

For sending the HTTP response we use @ResponseBody. So here is example for the same.

@ResponseBody example
@Controller
@RequestMapping("/products")
public class ProdController {

	@Autowired ProdService prodService;
	@ResponseBody @RequestMapping("/get")
	public Description getAllProducts(){
	    return prodService.saveProducts(products);
	}
}

@ModelAttribute

In simple words, The @ModelAttribute is used to send the data to web view as a model. This means it binds methods parameter or return value that can be exposed to the web view.

@ModelAttribute example
@Controller
@RequestMapping("/products")
public class ProdController {

	@Autowired ProdService prodService;

	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public String saveProducts(@ModelAttribute("employee") Employee employee){
	    rreturn "prodView";
	}
}

@ExceptionHandler

To handle exceptions we simply use the @ExceptionHandler. here we can send the customized error to the client using with @ExceptionHandler. Please find below given example for the same.

@ExceptionHandler example
@ExceptionHandler(value = {  MyResourceNotFoundException.class })
    protected ResponseEntity handleNotFound(final RuntimeException ex, final WebRequest request) {
        final String bodyOfResponse = "This should be application specific";
        String error = "Product not found.";
        return buildResponseEntity(new Error(HttpStatus.NOT_FOUND,error,ex) );

    }

@ResponseStatus

@ResponseStatus annotation is for setting the status code for unhandled exception. If we did not annotate with unhandled exception it will automatically set to 500.

@ResponseStatus example
@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "Product does not existed")
public class ProductNotFoundException extends RuntimeException {

    public ProductNotFoundException(int id) {
        super();
    }
}

@RequestHeader

@RequestHeader annotation will bind header values to the method as parameters. When the annotation @RequestHeader is used with method parameter then that parameter should be bound to the HTTP request header.

@RequestHeader example
@Controller
@RequestMapping("/products")
public class ProdController {

	@Autowired ProdService prodService;

	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public String saveProducts(@RequestHeader(value="User-Agent") String userAgent){
	    rreturn "prodView";
	}
}

Leave A Reply