Spring MVC multiple controller tutorial

Let us discuss spring mvc multiple controller example in eclipse.

Example Explanation:

Use http://localhost:8080/SpringMVCExample3/ url to start the application. When you click on any link, a request for respective resource will generate. Request will be handled by DispatcherServlet. The DispatcherServlet choose the controller with the help of HandlerMapping. It delegates the request to the specified controller. The specified controller resolve the request with help of RequestMapping annotation, executes the specific functionality and returns the ModelAndView object to the DispatcherServlet. The DispatcherServlet then take the help of InternalResourceViewResolver to get the actual view name. The DispatcherServlet then insert the model data into view and render response.

Example:

index.jsp



  
    Spring Multiple Controller Example.
  
  
    Say Hello 
    Say Welcome 
  

web.xml

  

   
   
      MultipleController
      
         org.springframework.web.servlet.DispatcherServlet
      
      1
   

   
      MultipleController
      *.html
   
 

MultipleController-servlet.xml

  


   

   
      
      
   
 

HelloController.java

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HelloController {
   @RequestMapping("/sayHello")  
   public ModelAndView sayHello() {
      String message = "Spring MVC Hello World Example.";
      return new ModelAndView("helloWorld", "message", message);  
   }
}

WelcomeController.java

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class WelcomeController {
   @RequestMapping("/sayWelcome")  
   public ModelAndView sayHello() {
      String message = "Welcome to the world of spring.";
      return new ModelAndView("welcome", "message", message);  
   }	
}

helloWorld.jsp



  
    Spring Multiple Controller Example.
  
  
    

${message}

welcome.jsp



  
    Spring Multiple Controller Example.
  
  
    

${message}

Output:

Spring example2-1
Click on Say Welcome link.
Spring example2-2
 
Download this example.