In Spring MVC, we use the @RestController annotation to develop RESTful Webservices, i.e. web controllers that read/write JSON/XML data based on standard HTTP methods (GET, POST, PUT, DELETE…). Let’s see a typical example:

package net.codejava.product;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ProductRestController {

	@Autowired ProductService service;
	
	@GetMapping("/products")
	public List<Product> getProducts() {
		return service.getProducts();
	}
}
In this example, the class is annotated with @RestController annotation which is itself annotated with @Controller and @ResponseBody annotations. That means:

- the @Controller annotation allows the controller to handle web requests with handler methods annotated with @RequestMapping annotation.

- the @ResponseBody annotation allows the object returned by the handler method to be serialized to JSON/XML in the response body. In the above example, the object of type List<Product> will be serialized to an array of JSON objects, with each representing product information, something like this:

[
  {
    "id": 1,
    "name": "iPhone 17",
    "price": 1700
  },
  {
    "id": 2,
    "name": "Kindle Fire",
    "price": 230
  },
  {
    "id": 3,
    "name": "Samsung Galaxy Tab",
    "price": 490
  }
]
 

That’s some code examples that help you understand the use of @RestController annotation in Spring framework, which is for developing RESTful Webservices. To see the coding in a real life project, watch the following video:

 

Reference:

Annotation Interface RestController (Spring Docs)

 

Other Spring Annotations:



 


About the Author:

is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.



Add comment