How to create Spring MVC controllers:

Controllers provide access to the application behavior that you typically define through a service interface. Controllers interpret user input and transform it into a model that is represented to the user by the view. Spring implements a controller in a very abstract way, which enables you to create a wide variety of controllers.

Spring 2.5 introduced an annotation-based programming model for MVC controllers that uses annotations such as @RequestMapping, @RequestParam, @ModelAttribute, and so on. This annotation support is available for both Servlet MVC and Portlet MVC.

@Controller
public class HelloWorldController {

    @RequestMapping("/helloWorld")
    public ModelAndView helloWorld() {
        ModelAndView mav = new ModelAndView();
        mav.setViewName("helloWorld");
        mav.addObject("message", "Hello World!");
        return mav;
    }
}

Controllers implemented in this style do not have to extend specific base classes or implement specific interfaces. Furthermore, they do not usually have direct dependencies on Servlet or Portlet APIs, although you can easily configure access to Servlet or Portlet facilities.

The @Controller and @RequestMapping annotations allow flexible method names and signatures. In this particular example the method has no parameters and returns a ModelAndView, but various other (and better) strategies exist, as are explained later in this section. ModelAndView, @Controller, and @RequestMapping form the basis for the Spring MVC implementation. This section documents these annotations and how they are most commonly used in a Servlet environment.

Doubts? WhatsApp me !