注解式SpringMVC程序

1:注册组件扫描器与驱动

在springMVC.xml中加入如下代码,删除以前写的单一class Bean.如果有静态资源<mvc:resources,必须注册驱动,要不然会报错。

 <!--注册驱动-->
  <mvc:annotation-driven/>
 <!--注册组件扫描器-->
  <context:component-scan base-package="com.davis.*"/>
  

2:@Controller

Controller类加注解@Controller,不需要实现接口implement Controller.导包org.springframework.stereotype.Controller;

@Controller
public class HelloSpringMVC {

}

3:@RequestMappging("")

Controller方法中加注解,映射浏览器响应路径

@Controller
public class HelloSpringMVC {

  @RequestMapping("/china/hello.do")
  public ModelAndView handleRequest(HttpServletRequest arg0, HttpServletResponse arg1) throws Exception {
      ModelAndView mv = new ModelAndView();
      mv.addObject("hello", "hello first spring mvc");
      mv.setViewName("first");
      return mv;
  }
}