Flat Preloader Icon

Spring MVC Multiple Controller

  • In a Spring MVC application, you can have multiple controllers to handle different parts of your application. Each controller is responsible for handling specific URLs or requests. Here’s how to create and configure multiple controllers in a Spring MVC application:

Step 1: Create Multiple Controller Classes

  • Create separate controller classes for different parts of your application. Each controller should be annotated with @Controller and define methods to handle specific URLs or request mappings.
  • For example, let’s create two controller classes: HomeController and ProductController.
public class HomeController {
    public String home() {
        return "home"; 
        // Return the view name 
        (e.g., home.jsp)

public class ProductController {
    public String productList() {
        return "productList"; 

    public String productDetails
    (@PathVariable Long id,
    Model model) {
// Logic to fetch product details by id and 
        add them to the model
       return "productDetails"; 
       // Return the view name 
        (e.g., productDetails.jsp)


Step 2: Create Corresponding JSP Views

  • For each controller, create JSP views in the src/main/webapp/WEB-INF/views directory. Name the views according to the view names returned by the controllers.
  • For example, if the HomeController returns “home,” create a home.jsp file. If the ProductController returns “productList,” create a productList.jsp file.

Step 3: Configure View Resolver

  • In your Spring MVC configuration (e.g., dispatcher-servlet.xml), configure the view resolver to resolve view names to JSP files.
					<bean class="org.springframework
    <property name="prefix" 
    value="/WEB-INF/views/" />
    <property name="suffix" value=".jsp" />


Step 4: Access Multiple Controllers and Views

Now, you can access the different controllers and views by navigating to their corresponding URLs:
  • To access the home page, visit http://localhost:8080/your-web-app-context/.
  • To access the product list, visit http://localhost:8080/your-web-app-context/products.
  • To access the product details for a specific product (e.g., with ID 123), visit http://localhost:8080/your-web-app-context/product/123.
  • Replace your-web-app-context with the context path of your deployed application.
By creating multiple controllers, you can organize your Spring MVC application into different functional areas, each with its own controller class and associated views. This allows for a modular and maintainable application structure.