🚀 @RestController vs @Controller — Do You Know the Real Difference? Most Spring Boot developers reach for @RestController without thinking twice. But knowing why it exists separates good engineers from great ones. @Controller is the classic Spring MVC annotation — it marks a class as a web controller that returns view names (like Thymeleaf templates). To return JSON from a @Controller method, you must explicitly add @ResponseBody. @RestController is simply a convenience annotation that combines @Controller + @ResponseBody. Every method automatically serializes the return value to JSON/XML via Jackson — no extra annotation needed. // Classic MVC — returns a Thymeleaf view @Controller public class PageController { @GetMapping("/home") public String home(Model model) { model.addAttribute("user", "Janis"); return "home"; // resolves to home.html } } // REST API — returns JSON automatically @RestController @RequestMapping("/api/users") public class UserController { @GetMapping("/{id}") public User getUser(@PathVariable Long id) { return userService.findById(id); // auto-serialized to JSON } } The rule is simple: → Building a REST API? Always use @RestController. → Building server-side rendered views (SSR)? Use @Controller. In modern microservice architectures, @RestController dominates — because APIs communicate via JSON, not HTML pages. #Java #SpringBoot #BackendDevelopment #REST #WebDevelopment #SoftwareEngineering
Jānis Ošs’ Post
More Relevant Posts
-
How DispatcherServlet Works Internally in Spring Boot 👇 🌱 Understanding How DispatcherServlet Works Internally in Spring Boot🚀 In Spring Boot applications, every HTTP request is handled by a central component called DispatcherServlet. It acts as the Front Controller of the Spring MVC architecture. This means all incoming requests first pass through DispatcherServlet, which decides how they should be processed. 🔍 What is DispatcherServlet? DispatcherServlet is the core component of Spring MVC responsible for: Receiving HTTP requests Finding the correct controller Executing business logic Returning the response to the client It acts as a traffic controller for web requests. 🔄 Internal Working Flow 1️⃣ Client Sends Request Example request: GET /users/1 The request first reaches DispatcherServlet. 2️⃣ Handler Mapping DispatcherServlet asks HandlerMapping: “Which controller should handle this request?” Spring finds the appropriate controller method. Example: @GetMapping("/users/{id}") public User getUser(@PathVariable int id) { return userService.getUser(id); } 3️⃣ Handler Adapter DispatcherServlet calls HandlerAdapter to execute the controller method. This step ensures that different types of handlers can be executed uniformly. 4️⃣ Controller Executes Logic The controller calls: Service Layer Repository Layer Database to process the request. 5️⃣ Response Returned Controller returns data: JSON (REST API) View (HTML page) Example: { "id": 1, "name": "John" } 6️⃣ View Resolver (For MVC Apps) If the application returns a view name, Spring uses ViewResolver to locate the actual view. Example: return "home"; Spring finds: home.html 📊 Complete Request Flow Client Request ⬇ DispatcherServlet ⬇ HandlerMapping ⬇ HandlerAdapter ⬇ Controller ⬇ Service ⬇ Repository ⬇ Response Returned to Client #SpringBoot #SpringMVC #Java #BackendDevelopment #LearningInPublic #JavaDeveloper
To view or add a comment, sign in
-
-
Filter vs Interceptor in Spring Boot 👇 🌱 Understanding Filter vs Interceptor in Spring Boot 🚀 While working with web applications in Spring Boot, we often need to perform tasks like: Logging requests Authentication & authorization Request validation Performance monitoring To handle these before or after a request, Spring provides Filters and Interceptors. Let’s understand the difference. 🔹 What is a Filter? A Filter is part of the Servlet API and works at the web container level. It processes requests before they reach the Spring application. Common use cases: Logging CORS handling Authentication Request/Response modification Example Filter: @Component public class LoggingFilter implements Filter { public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { System.out.println("Request received"); chain.doFilter(request, response); System.out.println("Response sent"); } } 🔹 What is an Interceptor? An Interceptor is part of Spring MVC and works inside the Spring framework. It intercepts requests before they reach the controller and after controller execution. Common use cases: Authentication checks Logging Request timing Authorization Example Interceptor: public class LoggingInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { System.out.println("Before controller execution"); return true; } } 🔄 Request Processing Flow Client Request ⬇ Filter ⬇ DispatcherServlet ⬇ Interceptor ⬇ Controller ⬇ Response Returned 🧠 Simple Way to Remember 👉 Filter → Works before Spring MVC 👉 Interceptor → Works inside Spring MVC #SpringBoot #SpringMVC #Java #BackendDevelopment #LearningInPublic #JavaDeveloper #SoftwareEngineering
To view or add a comment, sign in
-
-
Spring Security: Servlet vs. Reactive – Which one to choose? 🛡️ Choosing between Servlet and Reactive isn’t just a technical choice… 👉 It’s an architectural decision that directly impacts scalability, performance, and debugging. Here’s a quick breakdown from my recent learnings 👇 🔵 Servlet Stack (Spring MVC) Built on the Servlet API Uses Filters + SecurityContextHolder (ThreadLocal) Follows blocking I/O + thread-per-request model ✅ Best suited for: Traditional applications RDBMS-heavy systems Business logic–intensive services (Payments, Orders) ⚠️ Limitation: Threads remain occupied during I/O → limits scalability under high load 🟢 Reactive Stack (WebFlux) Built on Project Reactor Uses WebFilter + ReactiveSecurityContextHolder Follows non-blocking I/O + event-loop model ✅ Best suited for: High-concurrency microservices API Gateways / Streaming / Notifications Cloud-native, event-driven systems ⚠️ Challenge: Debugging async flows is harder Requires a shift in thinking (no ThreadLocal) 💡 Key Insight: 👉 It’s not about which is better 👉 It’s about where it fits My rule of thumb: 🔹 CPU-heavy → Servlet 🔹 I/O-heavy → Reactive ⚠️ One important lesson: You cannot mix both stacks in a single Spring Boot app cleanly. Spring will default to Servlet → Reactive may silently break. 📚 Still learning and exploring deeper into backend systems, trying to understand things beyond just configuration. 💬 Would love to hear from others — Which stack are you using in your projects? #SpringBoot #SpringSecurity #Java #BackendDevelopment #Microservices #WebFlux #LearningInPublic #Developers
To view or add a comment, sign in
-
🚀 ✨Spring MVC Architecture – How a Request is Processed 👩🎓Understanding Spring MVC architecture helps developers know how web requests flow inside a Spring Boot application. 📌Let’s break down the request lifecycle step by step 🔹 1. Client Request A user sends an HTTP request from the browser. 🔹 2. DispatcherServlet The request first reaches the DispatcherServlet, which acts as the Front Controller in Spring MVC. 🔹 3. Handler Mapping DispatcherServlet asks HandlerMapping to identify which controller should handle the request. 🔹 4. Handler Adapter Once the controller is identified, HandlerAdapter helps invoke the appropriate controller method. 🔹 5. Controller The Controller receives the request and delegates the work to the Service layer. 🔹 6. Service Layer (Business Logic) This layer contains the core business logic and interacts with the Repository layer. 🔹 7. Repository Layer (Data Access) Repository communicates with the Database to fetch or store data. 🔹 8. Model & View Resolver The controller returns data as a Model and a view name. The ViewResolver maps the view name to the actual view (JSP, Thymeleaf, etc.). 🔹 9. View Rendering The View displays the processed data to the user. 🔹 10. Response to Client Finally, the response is sent back to the client browser. 📌 Key Components of Spring MVC • DispatcherServlet • HandlerMapping • HandlerAdapter • Controller • Service • Repository • ViewResolver • View • Model 💡 Why Spring MVC is Powerful? ✅ Clear separation of concerns ✅ Scalable architecture ✅ Easy integration with Spring Boot ✅ Clean MVC design pattern Understanding this flow is essential for Java Backend Developers and helps during Spring Boot interviews. #SpringBoot #SpringMVC #Java #BackendDevelopment #SoftwareEngineering #JavaDeveloper #Programming #TechLearning #ParmeshwarMetkar
To view or add a comment, sign in
-
-
🚀 Spring Web MVC vs WebFlux — Simple Explanation with Real-Life Analogy As I continue exploring microservices and API Gateway, I wanted to clearly understand the difference between Spring Web (MVC) and Spring WebFlux. Here’s a simple breakdown 👇 🔹 Spring Web MVC (Blocking) Follows one request = one thread The thread waits until the task (like DB call) is completed 📌 Example: @GetMapping("/user") public User getUser() { return userService.getUser(); // blocking call } 👉 If 1000 users send requests, you need 1000 threads 👉 More threads = more memory usage & slower performance ⚡ Spring WebFlux (Non-Blocking) Uses reactive programming (Mono / Flux) A few threads can handle many requests No waiting — everything works asynchronously 📌 Example: @GetMapping("/user") public Mono<User> getUser() { return userService.getUser(); // non-blocking } 🍜 Simple Analogy Spring MVC (Blocking): You go to a restaurant, order food, and stand at the counter until it’s ready. ➡️ You are stuck waiting. Spring WebFlux (Non-blocking): You order food, get a token, sit down, and come back when your order is ready. ➡️ Your time is used efficiently. 🎯 When to Use What? ✅ Use Spring MVC → CRUD apps, simple systems ✅ Use WebFlux → API Gateway, microservices, high concurrency apps 💡 My Takeaway: WebFlux is powerful for scalability, but it requires a reactive mindset. Choosing the right approach depends on your use case. #SpringBoot #Java #WebFlux #Microservices #BackendDevelopment #SoftwareEngineering #LearningJourney
To view or add a comment, sign in
-
🔹Mastering the Flow of Spring MVC:- The Spring MVC framework is one of the most widely used modules in the Spring ecosystem for building web applications. To truly master it, it's important to understand how the code flows behind the scenes. 1. Request Flow Begins (Client → Server) When a user sends a request (via browser or API), it first reaches the DispatcherServlet, which acts as the Front Controller in Spring MVC. It is responsible for: 1.Receiving all incoming requests 2.Deciding which controller should handle them 2. Handler Mapping (Finding the Right Controller) The DispatcherServlet consults Handler Mapping to identify the correct controller method based on: 1.URL pattern 2.HTTP method (GET, POST, etc.) Example: /login → LoginController → login() method 3. Controller Handles the Request The controller processes the request: 1.Accepts input data (form data, query params, JSON, etc.) 2.Calls the business logic (Service layer) 3.Prepares the response Controllers are annotated with: @Controller or @RestController 4. Business Logic (Service Layer) The controller delegates work to the Service layer, where actual logic is written. Responsibilities: 1.Processing data 2.Applying business rules 3.Interacting with repositories/DAO 5. Data Access (DAO / Repository Layer) If needed, the service communicates with the database through: 1.Repository or DAO classes 2.Uses technologies like JPA, Hibernate 6. Model Creation The controller adds data to a Model object, which will be used to render the view. Example: model.addAttribute("user", userData); 7. View Resolution The controller returns a logical view name (like "home"), and the View Resolver maps it to an actual page: 1.JSP 2.Thymeleaf 3.HTML 8. Response Sent Back Finally, the rendered view (or JSON response in REST APIs) is sent back to the client. #SpringMVC #SpringFramework #JavaDeveloper #BackendDevelopment #WebDevelopment #SoftwareDevelopment #Java #MVC #SoftwareArchitecture #Coding #DeveloperCommunity #TechSkills #Codegnan Anand Kumar Buddarapu Uppugundla Sairam Saketh Kallepu
To view or add a comment, sign in
-
Day 44 🚀 Diving Deeper into Spring MVC – From Request to Response Today, I worked on understanding how data flows in a Spring MVC application, and it was a really insightful hands-on experience. Initially, coming from a Servlet background, handling request data felt a bit manual and tightly coupled. But with Spring MVC, I explored a much cleaner and structured approach. 🔹 I used @RequestParam to capture user input directly from the request without relying on traditional request.getParameter() 🔹 Created a model class (Student) to organize and store the incoming data 🔹 Leveraged ModelAndView to send data from the Controller to the View layer (JSP) 🔹 Configured View Resolver using prefix and suffix, which maps logical view names to actual JSP files One thing that really stood out to me was how Spring abstracts the complexity of request handling and promotes a clear separation of concerns. 👉 Controller → Handles request logic 👉 Model → Holds application data 👉 View → Displays the response 💡 Key Learning: Instead of writing boilerplate code, Spring allows us to focus more on business logic by simplifying how data is received, processed, and displayed. ⚡ While implementing this, I faced a few issues, but debugging step by step helped me understand the internal working of Spring MVC much better — especially how data binding and view resolution actually happen behind the scenes. 📌 This is just the beginning! Next, I’m planning to explore: ➡️ @ModelAttribute for automatic data binding ➡️ Form handling in a more scalable way ➡️ Building a complete MVC-based application Every small step is helping me move closer to becoming a better Backend Developer. #SpringMVC #SpringBoot #Java #BackendDevelopment #LearningJourney #FullStackDeveloper #Programming
To view or add a comment, sign in
-
-
🚀 Today I have gone through Spring Boot Deep Dive and found below major differences. 👉 @Controller vs @RestController This is a fundamental concept every Java backend developer must understand 👇 🔹 @Controller - Used in traditional Spring MVC applications - Mainly returns Views (like HTML, JSP, Thymeleaf) - Works with ModelAndView - If you want to return JSON, you must add @ResponseBody Example: @Controller public class PageController { @GetMapping("/home") public String home() { return "home"; // returns HTML page } } 👉 Here, Spring looks for a view (home.html) 🔹 @RestController - Special version of @Controller - Internally = @Controller + @ResponseBody - Used to build REST APIs - Returns data directly (JSON/XML) instead of Views Example: @RestController public class ApiController { @GetMapping("/api") public String api() { return "Hello World"; // returned as JSON response } } 👉 No view resolution happens here ⚡ Key Differences: ✔ @Controller → Returns View ✔ @RestController → Returns Data (JSON/XML) ✔ @Controller → Used in Web Apps ✔ @RestController → Used in REST APIs ✔ @Controller → Needs @ResponseBody for JSON ✔ @RestController → No need (already included) 🎯 When to use what? 👉 Use @Controller - When building UI-based applications - When working with server-side rendering 👉 Use @RestController - When building backend services / microservices - When exposing APIs for frontend (React, Angular, Mobile apps) 💡 Pro Tip (Important for Interviews): @RestController simplifies API development and is widely used in modern Spring Boot applications. #Java #SpringBoot #BackendDevelopment #RESTAPI #CodingInterview #SoftwareEngineer
To view or add a comment, sign in
-
Real world projects in production... At Architectural level - Java (Spring boot) 1) AOP implementation 2) Cache management 3) Interceptor 4) Global exception handling 5) Thread management 6) database integration 7) Microservices communication At Architectural level - Angular 1) Microfrontend communication. (using Module federation) 2) shared library to share components , directives between different microfrontends. 3) proxy file (CORS) to connect with backend (Java) 4) Generic components 5) cache management 6) Prevention from different attacks like... XSRF, XSS etc. At service level (Java): 1) Always use Composition over inheritance 2) Validations like @notnull, @notEmpty etc.. 3) use of var keyword 4) memeory leak prevention through weakHashMap 5) MVC: creating a controller , model, repository and service file. 6) use of virtual threads for multi-Threaded Environment. 7) Use of signals instead of traditional approach of for loop iterations. At Component Level (Angular) 1) creating directives and pipes. 2) use of scss for styling different components 3) use of structural directives @If, @for track: trackId 4) use of @defer for lazy loading of components 5) routing file for different routes let say /home, /dashboard, /user/:id etc... 6) standalone components 7) Use of Signals for forms and reactive programming 8) Interpolation 9) two way binding through ngModel Integration of frontend and backend and database is done with 1) At frontend (Angular) , field--> target: 'http://localhost:8080' in proxy.json file. (let's say your backend Java is running on localhost:8080) 2) At backend (Java) , application.properties file has i) base URL /api (org/system name), ii) server.port=8080 iii) database url: spring.datasource.url=jdbc:mysql://localhost:3306/your_db_name (let's say mySQL is running on localhost:3306.) Hope this helps! 😊 #architecture #angular #integration #realworldprojects #productionscale #java #springboot #javafullstack #springboot #mysql #latestfeatures
To view or add a comment, sign in
-
🚀 Exception Handling in Spring Boot While building backend applications, errors are unavoidable. For example: User not found Invalid input Server issues If we don’t handle these properly, the application can return confusing or messy errors. 👉 This is where Exception Handling becomes important. ❌ Without Exception Handling The application may return: Raw error messages Stack traces Poor user experience ✅ With Exception Handling We can return clean and meaningful responses to the client. Example: @ResponseStatus(HttpStatus.NOT_FOUND) public class UserNotFoundException extends RuntimeException { public UserNotFoundException(String message) { super(message); } } 🔹 Global Exception Handler @ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(UserNotFoundException.class) public ResponseEntity<String> handleException(UserNotFoundException ex) { return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND); } } 💡 Why this is important ✔ Improves user experience ✔ Makes APIs more professional ✔ Helps debugging ✔ Commonly asked in interviews Handling errors properly is a key step in building production-ready backend applications. #Java #SpringBoot #BackendDevelopment #ExceptionHandling #LearningInPublic
To view or add a comment, sign in
-
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development