🚀 @Controller vs @RestController in Spring Boot While learning Spring Boot, I came across two annotations that looked very similar: @Controller and @RestController At first, I thought they were the same… but they are used for different purposes. 🔹 @Controller Used in Spring MVC applications Returns HTML views (web pages) Often used with Thymeleaf or JSP Example: @Controller public class HomeController { @GetMapping("/home") public String home() { return "home"; } } This returns an HTML page named home. 🔹 @RestController Used for REST APIs Returns JSON or data directly Common in backend services Example: @RestController public class UserController { @GetMapping("/users") public List<User> getUsers() { return userService.getAllUsers(); } } This returns data in JSON format instead of a web page. 💡 Simple Way to Remember @Controller → Returns Views (HTML) @RestController → Returns Data (JSON) If you are building APIs for React, mobile apps, or frontend applications, you will mostly use @RestController. #Java #SpringBoot #BackendDevelopment #LearningInPublic #TechJourney
Spring Boot @Controller vs @RestController: Views vs Data
More Relevant Posts
-
Today I learned about Spring MVC and honestly… it changed how I think about web apps. 🧠 Before this, I had no idea how hitting a URL like /products returns a full page or JSON response. Now I know — it's the DispatcherServlet doing all the heavy lifting! Key annotations I learned today: 🔸 @Controller – marks the class as a web controller 🔸 @GetMapping – maps GET requests to a method 🔸 @RequestParam – reads query parameters 🔸 @PathVariable – reads values from the URL 🔵Here's a quick summary of the flow: ➡️Client sends an HTTP request (e.g., hitting /products) ➡️DispatcherServlet is the single entry point — it receives every request (that's why it's called the "front controller") ➡️It consults HandlerMapping to find which controller method should handle the URL ➡️The Controller runs your business logic and populates the Model with data ➡️It returns a ModelAndView object back to DispatcherServlet ➡️ViewResolver maps the view name (e.g., "products") to the actual template file (products.html) ➡️The View renders the final HTML/JSON response back to the client Small steps every day. 🚶 If you're also learning Spring, let's connect and grow together! 🤝 #Java #SpringMVC #SpringBoot #PlacementPrep #LearningInPublic #BackendDevelopment
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
-
🚀 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
-
@Controller vs @RestController – MVC vs REST (Spring Boot) While working on Spring Boot projects, one thing that really helped me gain clarity was understanding the difference between @Controller and @RestController. Here’s a simple breakdown 🔹 @Controller (Used in MVC) Returns View (JSP/HTML pages) Used when building traditional web applications Works with ModelAndView or Model to send data to UI Example: Returning a JSP page for user dashboard Best for: Web apps where UI is rendered on server side 🔹 @RestController (Used in REST APIs) Returns JSON / XML data directly No view resolution Combines @Controller + @ResponseBody Used in APIs for frontend (React, Angular, Mobile apps) Best for: Backend APIs / Microservices Key Difference: @Controller → Returns View @RestController → Returns Data (JSON/XML) In real-world projects: Use @Controller when you are working with JSP/Thymeleaf (MVC) Use @RestController when building REST APIs for frontend or mobile apps This distinction became very clear to me while building real-world projects using Spring Boot and REST APIs. #SpringBoot #Java #WebDevelopment #BackendDeveloper #MVC #RESTAPI #LearningJourney
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
-
-
🚀 Built a Full Stack Application using Spring Boot + React I recently worked on a project where I implemented both backend and a basic frontend. 🔧 Backend: • Developed using Spring Boot • Implemented Controller, Service, Repository layers • Built REST APIs for handling client requests • Connected with H2 in-memory database 🎨 Frontend: • Created a simple UI using React • Integrated frontend with backend APIs ⚙️ Features: • CRUD operations (Create, Read, Update, Delete) • Proper layered architecture • API integration between frontend and backend 💡 Key Learnings: • How data flows from UI → Backend → Database • Importance of structured backend architecture • Hands-on experience with full stack development 🎯 Next Goals: • Use MySQL instead of H2 • Improve UI/UX • Add validation and error handling This project gave me a clear understanding of how real-world applications are built. #SpringBoot #React #FullStack #Java #BackendDevelopment #WebDevelopment
To view or add a comment, sign in
-
🌐 Spring MVC – Building Scalable Web Applications Spring MVC (Model-View-Controller) is a powerful module of the Spring Framework used to build robust and scalable web applications. It follows the MVC design pattern, which helps in separating application logic, user interface, and control flow. In Spring MVC, the application is divided into three main components: 🔹 Model – Represents the data and business logic of the application. It interacts with the database and processes data. 🔹 View – Responsible for presenting data to the user (JSP, Thymeleaf, HTML, etc.). 🔹 Controller – Handles user requests, processes them, and returns the appropriate response (view or data). The flow in Spring MVC works as follows: A client sends a request → The DispatcherServlet receives it → The request is mapped to a controller → The controller processes the request → The model is updated → The appropriate view is returned to the user. Spring MVC provides features like: ✔️ Clean separation of concerns ✔️ Flexible request handling ✔️ Easy integration with other Spring modules ✔️ Support for RESTful web services By using Spring MVC, developers can build maintainable, testable, and scalable web applications efficiently. Understanding Spring MVC is a key step toward mastering Java backend development 🚀 Thank you sir Anand Kumar Buddarapu #Java #Spring #SpringMVC #WebDevelopment #BackendDevelopment #Programming #TechLearning
To view or add a comment, sign in
-
-
Every time I needed a UI for my Spring Boot project, the answer was always the same - "just learn React." Learn a new language. A new ecosystem. A new build system. Just to render a button. So I started thinking - why doesn't Java have its own frontend framework? One that compiles to WebAssembly and runs in the browser. No JavaScript required. That idea became SpringUI. ☕ SpringUI is a React-inspired frontend framework for Java developers. Write components in Java → compile to WASM → run in the browser. With @BindAPI, your components auto-wire directly to Spring Boot endpoints. No fetch(). Just Java, all the way down. Star it if this resonates. Contribute if you want to build something real. 🔗 https://lnkd.in/g3TzkcEp If you're a Java developer who's ever been told to "just learn JavaScript," this one's for you. Blazor proved this works for C#. Kotlin/Compose is proving it for Kotlin. SpringUI is the bet for Java. #Java #SpringBoot #OpenSource #WebAssembly #Frontend
To view or add a comment, sign in
-
-
what is means by Full Stack Development? Full Stack Development is the practice of building the entire web application, including both the frontend (user-facing interface) and backend (server-side logic, API, and database). A full-stack developer handles the entire development lifecycle, combining frontend technologies (HTML, CSS, JavaScript, React) with backend languages (Node.js, Python, Java) and database management. #FullStackDeveloper #FullStackDevelopment #WebDevelopment #MySQL #UIUXDesign #SoftwareDevelopment #CodingLife #Programmer #HTML #DeveloperLife #FrontendDevelopment #BackendDevelopment #CSS #WebDesign #APIIntegration #ResponsiveDesign #ClientSide #ServerSide #JavaScript #Python #Java #ReactJS #NodeJS #Angular #SpringBoot #Django #MongoDB
To view or add a comment, sign in
-
🚀 Spring Framework 🌱 | Day 4 Spring Bean Scopes Made Simple (with Real-Life Examples) Understanding bean scopes in Spring is very important for writing efficient applications. Let’s break it down in a simple way 👇 👉 1. Singleton (Default Scope) Only one object is created for the entire application. 🏠 Real-life example: Think of it like a TV in your home – everyone uses the same TV. In Spring, all requests use the same bean instance. 👉 2. Prototype A new object is created every time it is requested. ☕ Real-life example: Ordering coffee at a café – every time you order, you get a new cup. In Spring, each request gets a fresh bean. 👉 3. Request Scope (Web apps only) One object per HTTP request. 🧾 Real-life example: Filling a form online – each request has its own data. Once the request ends, the object is gone. 👉 4. Session Scope One object per user session. 🛒 Real-life example: Shopping cart in an e-commerce app – items stay until you logout or session expires. 💡 Quick Summary: 👉 Singleton → One shared object 👉 Prototype → New object every time 👉 Request → One per HTTP request 👉 Session → One per user session 🚀 Pro Tip: Use the right scope based on your use case to avoid performance and memory issues. #SpringFramework #Java #BackendDevelopment #InterviewPrep #SoftwareEngineering
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