@Controller in Spring: Definition, Usage, and Examples
@Controller is an annotation that marks a class as a web controller to handle HTTP requests and return views. It tells Spring MVC that this class contains methods to process web requests and send responses, usually HTML pages.How It Works
Think of @Controller as a traffic director in a web application. When a user visits a website or sends a request, the controller decides which code should run to handle that request. It listens for specific web addresses (URLs) and runs the matching method to prepare a response.
Inside the controller, methods are linked to URLs using annotations like @GetMapping or @PostMapping. When a request matches, the method runs, often preparing data and choosing which webpage (view) to show. This is similar to a waiter taking your order and bringing the right dish.
Spring automatically detects classes marked with @Controller and manages them, so you don’t have to create or connect them manually. This makes building web apps faster and cleaner.
Example
This example shows a simple controller that responds to a web request at the URL /hello and returns a greeting view.
import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.ui.Model; @Controller public class HelloController { @GetMapping("/hello") public String sayHello(Model model) { model.addAttribute("message", "Hello, Spring Controller!"); return "greeting"; // name of the view (e.g., greeting.html) } }
When to Use
Use @Controller when you want to build a web application that responds to user requests with HTML pages or views. It is ideal for traditional web apps where the server prepares the webpage content before sending it to the browser.
For example, use @Controller to create pages like homepages, user profiles, or forms that users fill out. It helps organize your code by grouping related web request handlers in one place.
If you want to build REST APIs that return data like JSON instead of views, consider using @RestController instead.
Key Points
- @Controller marks a class as a web controller in Spring MVC.
- It handles HTTP requests and returns views (usually HTML pages).
- Methods inside use annotations like
@GetMappingto map URLs. - Spring automatically detects and manages controller classes.
- Use
@Controllerfor web apps that serve HTML, not just data.
Key Takeaways
@Controller marks a class to handle web requests and return views in Spring MVC.@Controller.@RestController instead.