Presentation Layer

Now we create a controller that handles the web requests dispatched via. DispatcherServlet. Let the name of the controller be PhoneController and put it under the package com.spring.demo.

@Controller:

  • Indicates that the annotated PhoneController class serves the role of a "Controller".
  • A stereotype of @Component for web layer.
  • To enable autodetection of such annotated controllers, you add component scanning to your configuration at servlet-context.xml.
<context:component-scan base-package = "com.spring.demo" />

@Autowired:

  • A Constructor or a setter method as to be autowired by Spring's dependency injection facilities.
  • The field is injected right after construction of the bean, before any config methods are invoked.
  • Autowires the bean by matching the data type in the configuration metadata

@RequestMapping

  • DispatcherServlet uses this annotation to dispatch the requests to the correct controller and the handler method.
  • Maps URLS or web requests onto specific handler classes like @RequestMapping("/phones") and handler methods like example @RequestMapping("/edit/{id}")
  • RequestMapping element value is a String array ( String[] ) so it can accept multiple URL paths.
  • The handler methods which are annotated with this annotation are allowed to have very flexible return types and method signatures. Can find the detail here.

@Qualifier:

  • Used along with @Autowired to remove the conflict by specifying which exact bean will be wired.

Created the following HomeController that will be used to return the default view for our application.

HomeController.java

package com.spring.demo;

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

@Controller
public class HomeController {

    @RequestMapping(value="/")
    public ModelAndView mainPage() {
        return new ModelAndView("home");
    }

    @RequestMapping(value="/index")
    public ModelAndView indexPage() {
        return new ModelAndView("home");
    }
}

results matching ""

    No results matching ""