Here you will know about all Spring Web & REST services related annotations which we mostly used while development of applications:
See Also :
- Java : Annotation Tutorial
- Spring Core Annotations
- Spring Bean Annotations
- Spring Boot Annotations
- Spring Scheduling Annotations
- Spring Data Annotations
- Spring Junit Annotations
- Restful Webservice & JAX-RS Annotations
- JAXB Annotations
- JUnit Annotations
- Hibernate & JPA Annotations
- EJB Annotations
Spring Web & REST Annotations
@RequestMapping
@RequestMapping can be configured using path, or it’s aliases, name and value. @RequestMapping annotations apply at class and method level as request handler methods inside the @Controller classes.
@RequestMapping parameters:
- URL : the method is mapped to
- method : compatible HTTP methods/li>
- params : filters requests based on presence, absence or value of HTTP headers
- headers : filters requests based on presence, absence or value of HTTP params
- consumes: which media types the method can consume in the HTTP request body
- produces: which media types the method can produce in the HTTP response body
@RequestMapping variants for HTTP methods:
- @GetMapping :For GET method
- @PostMapping : For POST method
- @PutMapping : For PUT method
- @DeleteMapping :For Delete Method
- @PatchMapping : For Patch Method
Example : Method level
@Controller class CarController { @RequestMapping(value = "/cars/welcome", method = RequestMethod.GET) String welcome() { return "Facing Issues On IT"; } }
Example :Class level (both are equivalent)
@RequestMapping at class level that provide default settings for all handler methods in as @Controller class and for method handler URL that will be combination of path at class level and method level.
@Controller @RequestMapping(value = "/cars", method = RequestMethod.GET) class CarController { @RequestMapping("/welcome") String welcome() { return "Facing Issues on IT"; } }
@RequestBody
@RequestBody map the body of Http request to an object. Deserialization is automatic and depend on content type of request.
Example
@RequestMapping(value="/car/create", method=RequestMethod.POST) public ResponseEntity createCar(@RequestBody Car , UriComponentsBuilder ucBuilder){ System.out.println("Creating Car "+car.getName()); if(userService.isUserExist(user)){ System.out.println("A Car with name "+car.getName()+" already exist"); return new ResponseEntity(HttpStatus.CONFLICT); } carService.saveCar(car); HttpHeaders headers = new HttpHeaders(); headers.setLocation(ucBuilder.path("/user/{id}").buildAndExpand(car.getId()).toUri()); return new ResponseEntity(headers, HttpStatus.CREATED); }
@PathVariable
@PathVariable indicates that a method argument is bound to a URI template variable. We can specify the URI template with the @RequestMapping annotation and bind a method argument to one of the template parts with @PathVariable. We can achieve this with the name or its alias, the value argument.
Example : Path variable with different name
@RequestMapping("/{id}") Car getCar(@PathVariable("id") long carId) { // ... }
Example : Path variable with same name
If the name of the part in the template matches the name of method argument then no need to specify the @PathVariable annotation.
@RequestMapping("/{carId}") Car getCar(@PathVariable long carId) { // ... }
Example : Path variable as optional
We can make @PathVariable as optional by setting the argument required to false.
@RequestMapping("/{id}") Car getCar(required = false) long id) { // ... }
@RequestParam
@RequestParam use to access HTTP request parameters. It has the same configuration options as the @PathVariable annotation. We can access them with the annotations @CookieValue and @RequestHeader respectively.
Example
@RequestMapping Car getCarDetailByParam(@RequestParam("id") long id) { // ... }
Example : Set defaultValue to make required false
In @RequestParam can inject default value by setting defaultValue (i.e required false) that will consider when spring founds no and empty value in request.
@RequestMapping("/price") Car buyCar(@RequestParam(defaultValue = "6") int seatCount) { // ... }
@ResponseBody
Mark a request handler method with @ResponseBody then Spring treats the result of the method as the response itself.
If annotate a @Controller class with @ResponseBody annotation then all request handler methods will use it.
Example
@ResponseBody @RequestMapping("/hello") String hello() { return "Facing Issues on IT"; }
@ExceptionHandler
@ExceptionHandler can use to declare a custom error handler method. Spring calls this method when a request handler method throws any of the specified exceptions.The caught exception can be passed to the method as an argument:
Example
@ExceptionHandler(IllegalAccessException.class) void onIllegalAccessException(IllegalAccessException exception) { // ... }
@ResponseStatus
@ResponseStatus annotation use to specify the desired HTTP status of the response if we annotate a request handler method with this annotation. We can declare the status code with the code argument, or its alias, the value argument. Also, we can provide a reason using the reason argument and also use it along with @ExceptionHandler:
Example
@ExceptionHandler(IllegalAccessException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) void onIllegalAccessException(IllegalAcessException exception) { // ... }
@Controller
We can define a Spring MVC controller with @Controller.
Example
As used in below example
@RestController
The @RestController combines @Controller and @ResponseBody.
Example
Both are alternate way to handle rest services
@Controller @ResponseBody class VehicleRestController { // ... }
or
@RestController class VehicleRestController { // ... }
@ModelAttribute
@ModelAttribute annotation can access elements that are already in the model of an MVC @Controller, by providing the model key.
- Like @PathVariable and @RequestParam no need to specify the model key if the argument has the same name.
- If we annotate a method with @ModelAttribute Spring will automatically add the method’s return value to model.
Example
@PostMapping("/assemble") void assembleCar(@ModelAttribute("car") Car carModel) { // ... }
or here model attribute name is same.
@PostMapping("/assemble") void assembleCar(@ModelAttribute Car car) { // ... }
Before Spring calls a request handler method, it invokes all @ModelAttribute annotated methods in the class. We can use below either way to get value of vehicle model attribute.
@ModelAttribute("car") Car getCar() { // ... }
or
@ModelAttribute Car car() { // ... }
@CrossOrigin
@CrossOrign annotation enables cross-domain communication for the annotated request handler methods. If we mark a class with @CrossOrgin then it applies to all request handler methods in it.
Example
@CrossOrigin @RequestMapping("/welcome") String welcome() { return "Facing Issues On IT"; }
You must be logged in to post a comment.