1.实现Controller接口
//只要实现controller接口,说明这是一个控制器,就会返回一个ModelAndView
public class ControllerTest1 implements Controller {
public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
ModelAndView mv = new ModelAndView();
mv.addObject("msg","ControllerTest1");
mv.setViewName("test");
return mv;
}
}
编写完毕后,去Spring配置文件中注册请求的bean;name对应请求路径,class对应处理请求的类
<?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.caicai.controller"/>-->
<!-- 让Spring MVC不处理静态资源 -->
<!-- <mvc:default-servlet-handler />-->
<!--
支持mvc注解驱动
在spring中一般采用@RequestMapping注解来完成映射关系
要想使@RequestMapping注解生效
必须向上下文中注册DefaultAnnotationHandlerMapping
和一个AnnotationMethodHandlerAdapter实例
这两个实例分别在类级别和方法级别处理。
而annotation-driven配置帮助我们自动完成上述两个实例的注入。
-->
<!-- <mvc:annotation-driven />-->
<!-- 视图解析器 -->
<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.caicai.controller.ControllerTest1">
</bean>
</beans>
编写前端test.jsp
缺点是:一个控制器中只有一个方法,如果要多个方法则需要定义多个Controller
一个controller实现这个接口,重写一个方法,一个方法对应一个匹配的url地址
2.使用注解@Controller
@Controller注解类型用于声明Spring类的实例是一个控制器
Spring中另外三个等同的注解:@Component,@Service,@Repository
为了保证Spring能找到你的控制器,需要在配置文件中声明组件扫描
<!-- 自动扫描指定的包,下面所有注解类交给IOC容器管理 -->
<context:component-scan base-package="nuc.ss.controller"/>
//通过return+controller注解,返回一个视图解析器
@Controller //表示这个类会被Spring托管
//被Controller注解的类中的所有方法,如果返回值是String,并且有具体的页面可以跳转,那么就会被视图解析器解析
public class ControllerTest2 {
@RequestMapping("/t2")
public String test1(Model model){
model.addAttribute("msg","ControllerTest2");
return "test";
}
}
我们的两个请求都可以指向一个视图(test),但是页面结果的结果是不一样的,从这里可以看出视图是被复用的,而控制器与视图之间是弱偶合关系。