赞
踩
实现控制器Controller接口的几种方式
测试demo
1.新建一个Moudle,springmvc-04-controller
2.编写一个Controller类,ControllerTest1
public class ControllerTest1 implements Controller {
@Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
ModelAndView mv=new ModelAndView();
mv.addObject("msg","Test1Controller");
mv.setViewName("test1");
return mv;
}
}
springmvc-servlet.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- 自动扫描指定的包,下面所有注解类交给IOC容器管理--> <context:component-scan base-package="com.lding.controller"></context:component-scan> <!-- 视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver " id="internalResourceViewResolver"> <!-- 前缀 --> <property name="prefix" value="/WEB-INF/jsp/"/> <!-- 后缀 --> <property name="suffix" value=".jsp"/> </bean> <bean name="/t1" class="com.lding.controller.ControllerTest1"></bean> </beans>
测试结果
说明
<!-- 自动扫描指定的包,下面所有注解类交给IOC容器管理-->
<context:component-scan base-package="com.lding.controller"></context:component-scan>
@Controller
public class ControllerTest2 {
//映射访问路径
@RequestMapping("/t2")
public String index(Model model){
//spring mvc会自动实例化一个Model对象用于向视图中传值
model.addAttribute("msg","ControllerTest2");
//返回视图位置
return "test1";
}
}
可以发现,我们的两个请求都可以指向一个视图,但是页面结果的结果是不一样的,从这里可以看出视图是被复用的,而控制器与视图之间是弱偶合关系。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。