📌 Spring Boot Annotation Series – Part 11 ✅ @Controller annotation The @Controller annotation is used to mark a class as a web controller in Spring MVC 👇 🔹 What is @Controller? @Controller is a specialization of @Component. It tells Spring: 👉 “This class will handle web requests.” 🔹 Why do we use @Controller? To handle HTTP requests To return web pages (views) To separate web layer from business logic 🔹 How does it work? When a request comes to the application: Spring maps the URL to a method in the controller The method processes the request Returns a view name (like an HTML page) 🔹 Simple example @Controller public class HomeController { @GetMapping("/home") public String home() { return "home"; // returns home.html } } 🔹 Important Note @Controller is mainly used for MVC applications that return views. If you want to return JSON responses (REST APIs), we usually use: 👉 @RestController 🔹 In simple words @Controller is used to handle web requests and return web pages. 👉 🧠 Quick Understanding @Controller handles web requests Returns view (HTML/JSP/Thymeleaf) Used in Spring MVC applications #SpringBoot #Java #ControllerAnnotation #BackendDevelopment #LearningInPublic
Spring Boot @Controller Annotation Explained
More Relevant Posts
-
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
-
-
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
-
-
📅 Spring Boot DAY 20 – @RestController vs @Controller Difference between @RestController & @Controller 👇 In Spring Boot, both annotations are used to handle HTTP requests — but their purpose is different. 🔹 @Controller @Controller is used in Spring MVC applications where we return a View (HTML page). ✔ Returns view name (like index.html ) ✔ Used with Thymeleaf / JSP ✔ Data is passed to the view using Model Example: @Controller public class HomeController { @GetMapping("/home") public String home(Model model) { model.addAttribute("message", "Welcome!"); return "home"; // returns home.html } } 👉 Best for Web applications (Frontend + Backend together) 🔹 @RestController @RestController is used in REST APIs where we return JSON or XML data instead of a view. ✔ Returns data directly ✔ Automatically converts Java object → JSON ✔ Used for backend services Example: @RestController public class UserController { @GetMapping("/user") public User getUser() { return new User(1, "Gajanan"); } } 👉 Output: { "id": 1, "name": "Gajanan" } 🔥 Key Difference @Controller@RestControllerReturns HTML ViewReturns JSON/XMLUsed in MVC appsUsed in REST APIsNeeds @ResponseBody to return JSONNo need for @ResponseBody💡 Important Concept 👉 @RestController = @Controller + @ResponseBody @ResponseBody tells Spring to write return value directly into HTTP response body. That’s why modern microservices & backend APIs use @RestController. 🚀 When to Use What? ✔ Building a website with UI → Use @Controller ✔ Building API for Mobile/Web frontend → Use @RestController Most modern backend applications use @RestController. #RestController #Controller #SpringBoot #JavaAPI #BackendDevelopment
To view or add a comment, sign in
-
-
🚀 Day 10/100: Spring Boot From Zero to Production Topic: Bean Scopes 🧩 Remember when we talked about Beans in Java? Quick recap: Beans are just instances of your classes that live inside the Spring Container. Spring manages their lifecycle and handles Dependency Injection so you don't have to manually "new" them up every time. But there is a lot more to it than just creating them. We need to talk about Bean Scopes. 1. The Default: Singleton By default, all beans in Spring are Singletons. This means Spring creates the instance once and shares that same exact instance every single time it’s needed. For components like Services, Repositories, or Controllers, a single instance is perfect because they are usually stateless they just perform actions. 2. The Alternative: Prototype But what if a single instance isn't enough? What if your bean holds state-specific data or thread-specific info where one user's data shouldn't leak into another's? That’s where the Prototype scope comes in. With this, Spring creates a brand-new instance every time the bean is requested. ⚠️ Word of caution: Use this wisely! Creating too many prototype beans when they aren't needed can put a heavy load on your memory. 3. Web-Aware Scopes If you are building web apps, Spring offers even more specialized scopes: Request Scope: A new bean for every single HTTP request. Session Scope: A bean that lives as long as the user's HTTP session. Choosing the right scope is all about balancing memory efficiency with data integrity. How do you usually decide between Singleton and Prototype in your projects? Let’s discuss below! 👇 #Java #SpringBoot #SoftwareDevelopment #100DaysOfCode #Backend
To view or add a comment, sign in
-
-
🚀 @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
To view or add a comment, sign in
-
Hi everyone 👋 Continuing the Spring Boot Annotation Series, today let’s understand one of the most important web annotations 👇 📌 Spring Boot Annotation Series Part 16– @RequestMapping The @RequestMapping annotation is used to map HTTP requests(like GET, POST etc) to handler methods in a controller. It is part of Spring Framework and is mainly used in Spring MVC. 🔹 What does @RequestMapping do? It defines: - URL path - HTTP method (GET, POST, etc.) - Request parameters - Headers - Consumes / Produces (Content-Type) 🔹 Basic Example - @RestController @RequestMapping("/api") public class UserController { @RequestMapping("/users") public String getUsers() { return "List of users"; } } 👉 This maps to: http://localhost:8080/api/users 🔹 Specifying HTTP Method - @RequestMapping(value = "/users", method = RequestMethod.GET) public String getUsers() { return "Users"; } But nowadays we prefer: @GetMapping("/users") 🔹 Where Can We Use It? ✅ At Class Level → Base URL ✅ At Method Level → Specific endpoint Example: @RequestMapping("/api") // class level @GetMapping("/users") // method level Final URL → /api/users 🔹 In Simple Words @RequestMapping connects a URL to a controller method. It tells Spring: “When this request comes, execute this method.” #SpringBoot #Java #SpringMVC #BackendDevelopment #InterviewPreparation #LearningInPublic
To view or add a comment, sign in
-
𝗠𝗼𝘀𝘁 𝗨𝘀𝗲𝗱 𝗔𝗻𝗻𝗼𝘁𝗮𝘁𝗶𝗼𝗻𝘀 𝗶𝗻 𝗦𝗽𝗿𝗶𝗻𝗴 𝗙𝗿𝗮𝗺𝗲𝘄𝗼𝗿𝗸 (𝗗𝗲𝘃𝗲𝗹𝗼𝗽𝗲𝗿𝘀 𝗠𝘂𝘀𝘁 𝗞𝗻𝗼𝘄!) Spring makes Java development faster and easier with powerful annotations that reduce boilerplate code and simplify configuration. Here are some of the most commonly used Spring annotations every developer should understand: ✅ @SpringBootApplication → Entry point of a Spring Boot app (combines @Configuration, @EnableAutoConfiguration, @ComponentScan) ✅ @Component → Marks a class as a Spring-managed bean ✅ @Service → Business logic layer bean ✅ @Repository → Data access layer bean with exception translation ✅ @Controller → Handles web requests (MVC) ✅ @RestController → Combines @Controller + @ResponseBody for REST APIs ✅ @Autowired → Automatically injects dependencies ✅ @RequestMapping → Maps HTTP requests to handler methods ✅ @GetMapping / @PostMapping / @PutMapping / @DeleteMapping → Shortcut HTTP method mappings ✅ @Configuration → Defines configuration class ✅ @Bean → Declares a bean manually ✅ @Value → Injects values from properties files 💡 Mastering these annotations helps you build scalable, clean, and production-ready Spring applications faster. #SpringBoot #SpringFramework #JavaDeveloper #BackendDevelopment #RESTAPI #Microservices #JavaProgramming #SoftwareDevelopment #Programming #TechLearning
To view or add a comment, sign in
-
🌐 Day 14/15 – Revision: Mastering Servlet & JSP 🚀 3 Powerful Servlet Concepts Every Java Developer Should Know Many developers learn Servlets, but understanding these 3 concepts with real-life examples makes the difference in interviews and real projects. 1️⃣ load-on-startup Normally, a servlet is created only when the first request comes. But sometimes we want the servlet to be ready when the server starts. 👉 That’s where load-on-startup helps. Real Example Imagine a bank ATM machine. If the ATM loads software only when the first customer arrives, the customer must wait. Instead, the ATM loads everything when the machine starts so customers can use it instantly. Same with Servlet. <load-on-startup>1</load-on-startup> ✔ Preloads servlet ✔ Improves first request performance ✔ Used for configuration or cache initialization 2️⃣ Filters Filters act like a security checkpoint before the request reaches the servlet. Real Example Think about airport security ✈️ Panger → Security Check → Boarding Gate Similarly: User Request → Filter → Servlet Filters are commonly used for: ✔ Authentication ✔ Logging ✔ Request validation ✔ Response modification Example: LoginFilter → Check User Session → Allow Request 3️⃣ Listeners Listeners observe application events and react automatically. Real Example Think about a motion sensor light 💡 When someone enters → Light turns ON When nobody is there → Light turns OFF Similarly in web applications: User logs in → Session created User logs out → Session destroyed Example: HttpSessionListener Used for: ✔ Tracking active users ✔ Resource initialization ✔ Application monitoring 💡 Simple Way to Remember 👉load-on-startup → Prepare before request 👉Filter → Check request before processing 👉Listener → React when event happens 🔥 Interview Tip Many enterprise applications use: Filters for security Listeners for monitoring load-on-startup for initialization Understanding these concepts shows real project experience, not just theory. #Java #Servlet #JavaDeveloper #BackendDevelopment #Programming #TechLearning #JavaInterview #SoftwareDevelopment
To view or add a comment, sign in
-
-
🌐 Day 1/15 – Revision Journey: Mastering Servlet & JSP Today, I’m starting my 15-Day Revision Journey to Master Servlet & JSP — the strong foundation of Java Web Development. Before jumping into frameworks like Spring Boot, it’s important to understand how web actually works behind the scenes. 💡 What is a Servlet? A Servlet is a Java class that handles client requests and generates responses. 👉 Real-Life Example: Think of a bank counter officer. You (client) submit a form (request). The officer (Servlet) processes your request. You receive a receipt or response. Servlet works exactly like that — it receives HTTP request, processes it, and sends back response. 💡 What is JSP? JSP (JavaServer Pages) is used to create dynamic web pages. 👉 Real-Life Example: Imagine a restaurant menu board. The board (JSP page) displays items. But the kitchen (Servlet) prepares the food. 👉 Servlet = Logic handling 👉 JSP = Presentation layer Together, they follow the MVC (Model-View-Controller) pattern. 🌐 How Web Flow Works? 1️⃣ Client sends request 2️⃣ Web container like Apache Tomcat receives it 3️⃣ Servlet processes logic 4️⃣ JSP displays the result 5️⃣ Response goes back to client 🎯 Why This Still Matters? Even in modern frameworks like Spring Boot, the core concept is still based on Servlets internally. If you understand Servlet & JSP clearly, you understand the foundation of Java web architecture. Let’s build consistency, not just knowledge. #Java #Servlet #JSP #JavaWeb #BackendDeveloper #LearningJourney #15DaysChallenge #JavaDeveloper
To view or add a comment, sign in
-
-
🚀 Understanding MVC Architecture in Java Web Applications Today I created a simple diagram to understand how the MVC (Model–View–Controller) architecture works in a Java web application. 🔹 View (Presentation Layer) HTML, CSS, and JavaScript create the user interface (Login Form). 🔹 Controller (Business Logic Layer) Servlet/JSP receives the HTTP Request, processes the business logic, and controls the application flow. 🔹 Model (Data Layer) Using JDBC API, the application communicates with the database to store and retrieve data. 📌 Key Idea: MVC separates UI, business logic, and data access, making applications more organized, scalable, and maintainable. 💻 Tech Stack: Java | Servlet | JSP | JDBC | HTML | CSS | JavaScript | Database Always learning and improving my backend development skills. 💻🔥 #Java #MVC #BackendDevelopment #WebDevelopment #JDBC #Servlet #Programming #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