Loading

Quipoin Menu

Learn • Practice • Grow

spring / Multiple Controllers
interview

Q1. How do you configure multiple controllers in Spring MVC?
Simply define multiple classes annotated with @Controller, each with its own request mappings. Spring scans them and registers them as controllers. You can organize by functionality, e.g., UserController, ProductController. DispatcherServlet uses HandlerMapping to route requests based on URL patterns.

Q2. How does Spring know which controller to invoke for a request?
DispatcherServlet uses HandlerMapping implementations. The default is RequestMappingHandlerMapping which uses @RequestMapping annotations to map URLs to controller methods. It builds a registry of mappings and selects the first match.

Q3. Can two controllers have the same request mapping?
If they have identical mappings (same URL and HTTP method), Spring will throw an exception during initialization because the mapping would be ambiguous. To avoid, use different URL patterns or different HTTP methods.

Q4. What is @Controller vs @RestController?
@Controller is used for traditional MVC controllers that return views. @RestController is a convenience annotation combining @Controller and @ResponseBody, used for REST APIs where methods return domain objects directly (serialized to JSON/XML).

Q5. How do you pass data between controllers?
You can use session attributes, redirect attributes, or forward requests. For example, using RedirectAttributes to pass flash attributes across redirects. Or store data in the session via @SessionAttributes.