🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
🚀 Introduction: Understanding @RestController vs @RequestMapping
In Spring Boot, both @RestController and @RequestMapping are used in RESTful APIs, but they serve different purposes.
✅ Key Differences:
| Feature | @RestController |
@RequestMapping |
|---|---|---|
| Purpose | Marks a class as a REST controller (returns JSON responses). | Maps HTTP requests to controller classes or methods. |
| Applies To | Class level (on controllers) | Class and method level (for URL mappings) |
| Implicit Behavior | Includes @ResponseBody by default. |
Does not include @ResponseBody (must be explicitly added). |
| Common Usage | Used for REST APIs (microservices, JSON responses). | Used for defining request mappings in controllers. |
1️⃣ Understanding @RestController in Spring Boot
📌 Use @RestController to define RESTful APIs that return JSON responses.
✅ @RestController = @Controller + @ResponseBody
Example: Using @RestController for a REST API
@RestController
@RequestMapping("/api/users")
public class UserController {
@GetMapping("/{id}")
public User getUserById(@PathVariable int id) {
return new User(id, "Ramesh");
}
}
📌 How It Works:
- The class is marked as a REST API controller.
- The
@RestControllerannotation automatically applies@ResponseBody, so the return value is converted to JSON.
📌 Example API Response (GET /api/users/1):
{
"id": 1,
"name": "Ramesh"
}
✅ Ideal for building RESTful services that return JSON responses.
2️⃣ Understanding @RequestMapping in Spring Boot
📌 Use @RequestMapping to define URL mappings for controllers.
✅ It can be applied at class level and method level.
✅ It supports GET, POST, PUT, DELETE, PATCH requests.
Example: Using @RequestMapping at Class and Method Level
@Controller
@RequestMapping("/web")
public class WebController {
@RequestMapping(value = "/home", method = RequestMethod.GET)
public String homePage() {
return "home"; // Returns home.html (Thymeleaf/JSP view)
}
}
📌 How It Works:
- The
@RequestMappingat class level applies to all methods inside it (/web). - The method maps
/web/hometohome.html(a view page). - Unlike
@RestController, this method returns a view name, not JSON.
3️⃣ @RequestMapping in a REST API (Without @RestController)
📌 If you use @Controller, you must add @ResponseBody manually to return JSON.
@Controller
@RequestMapping("/api")
public class UserController {
@RequestMapping(value = "/users/{id}", method = RequestMethod.GET)
@ResponseBody
public User getUserById(@PathVariable int id) {
return new User(id, "Ramesh");
}
}
✅ Adding @ResponseBody ensures JSON output in REST APIs.
📌 Example API Response (GET /api/users/1):
{
"id": 1,
"name": "Ramesh"
}
✅ Equivalent to using @RestController, but requires @ResponseBody.
4️⃣ @GetMapping, @PostMapping, @PutMapping, @DeleteMapping vs @RequestMapping
Spring Boot provides shortcut annotations for common HTTP methods:
| Annotation | Equivalent @RequestMapping |
|---|---|
@GetMapping("/users") |
@RequestMapping(value = "/users", method = RequestMethod.GET) |
@PostMapping("/users") |
@RequestMapping(value = "/users", method = RequestMethod.POST) |
@PutMapping("/users/{id}") |
@RequestMapping(value = "/users/{id}", method = RequestMethod.PUT) |
@DeleteMapping("/users/{id}") |
@RequestMapping(value = "/users/{id}", method = RequestMethod.DELETE) |
✅ Using @GetMapping, @PostMapping, etc., makes the code cleaner and more readable.
5️⃣ When to Use @RestController vs @RequestMapping?
| Use Case | Use @RestController |
Use @RequestMapping |
|---|---|---|
| RESTful API (returns JSON) | ✅ Yes | ❌ No (Requires @ResponseBody) |
| MVC application (returns views) | ❌ No | ✅ Yes (For rendering HTML views) |
| Returning JSON responses | ✅ Yes (Automatic) | ❌ No (Needs @ResponseBody) |
| HTTP method-specific mappings | ✅ Yes (@GetMapping, @PostMapping, etc.) |
✅ Yes (@RequestMapping(method = ...)) |
📌 Best Practice:
✔ Use @RestController for REST APIs (JSON responses).
✔ Use @Controller + @RequestMapping for web applications (Thymeleaf, JSP).
6️⃣ Combining @RestController and @RequestMapping
📌 Example: Using @RestController with @RequestMapping for REST API
@RestController
@RequestMapping("/api/users")
public class UserController {
@GetMapping("/{id}")
public User getUserById(@PathVariable int id) {
return new User(id, "Ramesh");
}
}
✅ Combining @RestController and @RequestMapping makes REST API development easy.
🎯 Summary: Best Practices for @RestController and @RequestMapping
✅ Use @RestController when building REST APIs that return JSON.
✅ Use @Controller with @RequestMapping when building MVC applications.
✅ Use @GetMapping, @PostMapping, etc., instead of @RequestMapping(method = ...) for cleaner code.
✅ If using @Controller for REST, always add @ResponseBody manually.
🚀 Following these best practices ensures clean, maintainable Spring Boot applications!
📢 Share this guide with developers to help them master @RestController and @RequestMapping in Spring Boot! 🚀
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment