Real-World Analogy
`@Controller` is like a theater ticket usher—directing incoming visitors to their specific seating view (HTML page).
Spring MVC Web Controller
`@Controller` registers web controllers that return view names rendered by view resolvers.
Server-Side Template Rendering:
In traditional Web applications (built with Thymeleaf, FreeMarker, or JSP), @Controller methods return String view template names. Spring MVC's ViewResolver maps the returned string to a physical template file in resources/templates/.
- Model Injection: Inject
org.springframework.ui.Modelinto controller methods to pass data attributes to HTML views. - REST API Conversion: To return raw JSON instead of HTML view templates, combine
@Controllerwith@ResponseBodyor use@RestController.
Production Code Example:
package com.anujsingh.digitalguru.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class WebController {
@GetMapping("/home")
public String home() { return "home"; }
}
Key Architectural Concepts & Best Practices:
When working with @Controller in enterprise Spring Boot applications, keep these key architectural guidelines in mind:
- Separation of Concerns: Maintain a strict boundary between HTTP endpoints, service logic, and database persistence layers.
- Framework Conventions: Rely on Spring Boot auto-configuration defaults whenever possible, overriding settings only via
application.ymlor@Configurationclasses when customized behavior is required. - Production Monitoring & Reliability: Ensure proper exception handling, thread-safety, and resource cleanup to prevent memory leaks and unexpected runtime downtime.
- Developer Ergonomics: Write clean, self-documenting code with modern Java features (Records, Lambdas, Streams) to simplify code reviews and maintenance.
Summary Takeaway:
Mastering @Controller ensures that your Java & Spring Boot backend microservices remain maintainable, secure, and compliant with modern enterprise software engineering standards.
Difference
Returns HTML view template names unless combined with `@ResponseBody`.