Careeroza
RestController and GetMapping
A Controller Handles HTTP Requests
A class annotated with @RestController handles web requests. Each method annotated with @GetMapping("/path") answers GET requests to that path. Whatever the method returns is written into the response body (as JSON for objects).
package com.shopease.product;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello() {
return "Welcome to ShopEase!";
}
}Example
curl -i http://localhost:8080/helloExample output
HTTP/1.1 200 Content-Type: text/plain;charset=UTF-8 Content-Length: 20 Welcome to ShopEase!
@RestController vs @Controller
@Controller | @RestController | |
|---|---|---|
| Return value means | name of an HTML view (template) | the response body itself |
| Used for | server-rendered pages (Thymeleaf) | REST APIs (JSON) |
| Relation | - | @Controller + @ResponseBody on every method |
A Common Prefix
@RequestMapping on the class adds a prefix to every method in it:
@RestController
@RequestMapping("/api/products")
public class ProductController {
@GetMapping // GET /api/products
public List<String> names() {
return List.of("Boat Rockerz 450", "Clean Code", "Cotton T-Shirt");
}
@GetMapping("/count") // GET /api/products/count
public int count() {
return 3;
}
}Note: POST, PUT, PATCH, DELETE, @PathVariable, @RequestParam, @RequestBody and ResponseEntity are covered in Building REST APIs in the medium level. Here we focus on GET.