By default spring uses BeanNameUrlHandlerMapping, buth Spring MVC 3 also provides SimpleUrlHandlerMapping that also can be used to map urls to the controller. When a request comes in, the DispatcherServlet will hand it over to the handler mapping to let it inspect the request and come up with an appropriate HandlerExecutionChain. Then the DispatcherServlet will execute the handler and interceptors in the chain (if any). The concept of configurable handler mappings that can optionally contain interceptors (executed before or after the actual handler was executed, or both) is extremely powerful. A lot of supporting functionality can be built into custom HandlerMappings.




Maven configuration


You need the following jar files. So either add this pom.xml file to your application or download and add the jar files to your class-path.




AbstractController


Here, our HelloController class extends AbstractController class, that makes our class function as a controller and able to handle a request/response. If you extend AbstractController, you are omitted to override the handleRequestInternal method which will handle the request. We must return a ModelAndView object, this object contains a view name in our example 'index' which returns the index.jsp page. We also add an Object witch the identifier 'message'.


package org.camelcode.controller;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HelloController extends AbstractController {

    @Override
    protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
        ModelAndView modelAndView = new ModelAndView("index");
        modelAndView.addObject("message", "Hello, World!");
        return modelAndView;
    }
}


Spring ApplicationContext


We register our controller with the <bean/>. Then we register a SimpleUrlHandlerMapping witch is automatically detected by the dispatcher servlet. We can either register our url's with <property name="urlMap"/> or with <property name="mappings"/>. So we can map the same controller to different url's. Next is the InternalResourceViewResolver witch will forward the right view from the controller.




    

    
	
		
			
				
				
			
		
		
			
				helloController
				helloController
			
		
	

	
         
         
    



web.xml



JSP Page


Calling the following url's you can access the controller and display the correct view:

  • /hello.htm ?> /hello.htm
  • /sayHello.htm ?> /sayHello*
  • /sayHelloToAll.htm ?> /sayHello*
  • /welcome.htm ?> /welcome.htm




Screenshots


spring-mvc-hello-world


References