Saturday, February 9, 2013

@Controller and @RequestMapping

Since Spring 2.5 onwards, we can configure controllers through Spring Annotations which helps us in many ways.

  1. Spring bean definition files to be of minimal size.
  2. No need to extend any spring controllers and easy to create form and multi-action controller
@Controller:
Tells the spring framework that this class is used as a controller and should be considered by Dispatcher Servlet for delegating the requests to this controller.

@RequestMapping:
Tells the spring framework what are all the URLs that would be handled by this controller.

com.controller.test;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.servlet.ModelAndView;

@Controller("HelloWordController")

@RequestMapping("/hello")

public class HelloWorldController {

    @RequestMapping(value = "/world", method = RequestMethod.GET)

    public ModelAndView helloWord() {

        return new ModelAndView("HelloWorld");

    }

}

Now tell spring framework to scan your package for annotations. and define the HelloWorld webpage as per your requirement.

<context:component-scan base-package="com.controller.test" />

Thats it. Now deploy & start your application. Hit the below URL and see the actions.

http://localhost:8080/yourproject/hello/world

No comments:

Post a Comment