In this tutorial we are targeting AbstractController for xml based configuration. Spring MVC also supports annotation based configuration as of Spring 3. All of spring's controllers are inherited from AbstractController, The AbstractController provides the basic building blocks. You can extend the AbstractController class and the build your own controller from scratch. It is used for simple stuff like returning a resource to the client or redirecting.




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


In our ApplicationContext of Spring we register our controller with the name '/hello.htm'. By default spring 3 mvc will use BeanNameUrlHandlerMapping to resolve the url to controller class mapping. So our controller will listen to the url '/hello.htm'. The view resolver will resolve jsp pages from view name




web.xml


Now we have to register the dispatcherServlet of spring to work as a frotController.




Jsp page



Screenshots


spring-mvc-hello-world


References