Spring Boot web applications rely heavily on annotations to configure controllers, handle requests, and define responses.
Here’s a breakdown of the most commonly used Spring Web annotations with simple examples:
1. @RestController
- Combines
@Controller
and@ResponseBody
. - Marks a class as a web controller that directly returns data (usually JSON).
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.GetMapping;
@RestController
public class HelloController {
@GetMapping("/hello")
public String sayHello() {
return "Hello, Spring Boot!";
}
}
2. @RequestMapping
- Used at class level and method level to map HTTP requests to handler methods.
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/users")
public class UserController {
@GetMapping("/{id}")
public String getUser(@PathVariable int id) {
return "User with ID: " + id;
}
@PostMapping
public String createUser(@RequestBody String user) {
return "Created User: " + user;
}
}
3. @GetMapping
, @PostMapping
, @PutMapping
, @DeleteMapping
- Specialized versions of
@RequestMapping
for specific HTTP methods.
@RestController
@RequestMapping("/products")
public class ProductController {
@GetMapping
public String getAllProducts() {
return "List of products";
}
@PostMapping
public String addProduct(@RequestBody String product) {
return "Added product: " + product;
}
@PutMapping("/{id}")
public String updateProduct(@PathVariable int id, @RequestBody String product) {
return "Updated product " + id + " with: " + product;
}
@DeleteMapping("/{id}")
public String deleteProduct(@PathVariable int id) {
return "Deleted product with ID: " + id;
}
}
4. @PathVariable
- Extracts values from the URI path.
@GetMapping("/orders/{orderId}")
public String getOrder(@PathVariable int orderId) {
return "Order ID: " + orderId;
}
5. @RequestParam
- Extracts values from query parameters.
@GetMapping("/search")
public String search(@RequestParam String keyword) {
return "Searching for: " + keyword;
}
Example request:
GET /search?keyword=laptop
6. @RequestBody
- Maps the request body (usually JSON) to a Java object.
@PostMapping("/register")
public String registerUser(@RequestBody User user) {
return "Registered user: " + user.getName();
}
7. @ResponseBody
- Used on methods to indicate return value should go directly in the HTTP response (not a view).
(Since@RestController
already applies this, you’ll mostly use it in@Controller
classes.)
@Controller
public class MyController {
@GetMapping("/message")
@ResponseBody
public String getMessage() {
return "Direct Response Body";
}
}
8. @Controller
- Marks a class as a Spring MVC Controller (used when rendering views like JSP/Thymeleaf, not just JSON).
@Controller
public class WebController {
@GetMapping("/home")
public String homePage() {
return "home"; // returns "home.html" from templates
}
}