Multiple Controllers
A real restaurant has multiple waiters. One handles breakfast, another handles lunch, and a third handles dinner. Similarly, in Spring MVC, you can have multiple controllers to organize your code better.
Each controller handles a specific section of your application. For example:
UserController– handles login, registration, profile.ProductController– handles product listing, details, search.OrderController– handles cart, checkout, orders.
Here is how you create multiple controllers:
@Controller
@RequestMapping("/user")
public class UserController {
@GetMapping("/profile")
public String profile(Model model) {
model.addAttribute("username", "John");
return "user-profile";
}
@GetMapping("/settings")
public String settings() {
return "user-settings";
}
}
@Controller
@RequestMapping("/product")
public class ProductController {
@GetMapping("/list")
public String listProducts(Model model) {
model.addAttribute("products", Arrays.asList("Laptop", "Mouse", "Keyboard"));
return "product-list";
}
}
Notice the
@RequestMapping at class level. It adds a common prefix to all URLs in that controller. For example:/user/profile– handled by UserController.profile()/product/list– handled by ProductController.listProducts()
This keeps your URLs organized and your code clean.
Two Minute Drill
- Multiple controllers help organize code by feature/module.
- Use @RequestMapping at class level for common URL prefix.
- Each controller handles a specific domain (user, product, order).
- DispatcherServlet routes requests to the correct controller based on URL.
- This follows the Single Responsibility Principle.
Need more clarification?
Drop us an email at career@quipoinfotech.com
