1.Controller
1.实现Controller接口,这是一种比较老的方法,一个控制器中只有一个方法,如果要多个方法则需要定义多个Controller;定义的方式比较麻烦
//定义控制器
//注意点:不要导错包,实现Controller接口,重写方法;
public class ControllerTest1 implements Controller {
public ModelAndView handleRequest(HttpServletRequest
httpServletRequest, HttpServletResponse httpServletResponse) throws
Exception {
//返回一个模型视图对象
ModelAndView mv = new ModelAndView();
mv.addObject("msg","Test1Controller");
mv.setViewName("test");
return mv;
}
}
2, 编写完毕后,去Spring配置文件中注册请求的bean;name对应请求路径,class对应处理请求的类
<bean name="/t1" class="com.kuang.controller.ControllerTest1"/>
还有一种就是使用@Controller注解
将@Controller标注再类上,这时候不能说它就是springmvc的控制器,因为Spring容器还不认识它,需要在配置中声明,把这个控制器交给spring容器,让spring容器来管理。声明的方式有两种
第一种可以在配置中声明组件扫描器
<!-- 自动扫描指定的包,下面所有注解类交给IOC容器管理 -->
<context:component-scan base-package="com.kuang.controller"/>
第二种
<!--基于注解的装配-->
<bean class="com.HelloWorld"/>
一般都使用第一种来装配
2.RequestMapping
配置声明之后,@Controller只是定义了一个控制器类,而使用@RequestMapping注解的方法才是处理请求的处理器
@Controller
public class TestController {
@RequestMapping("/h1")
public String test(){
return "test";
}
}
访问路径:http://localhost:8080 / 项目名 / h1
@Controller
@RequestMapping("/admin")
public class TestController {
@RequestMapping("/h1")
public String test(){
return "test";
}
}
访问路径:http://localhost:8080 / 项目名/ admin /h1 , 需要先指定类的路径再指定方法的路径;