以下是调试mvc源码过程中用到的demo以及配置文件webapp/WEB-INF/web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:springmvc.xml</param-value>
</init-param>
<!-- load-on-startup元素标记容器是否在启动的时候就加载这个servlet(实例化并调用其init()方法) -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
springmvc.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
https://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
">
<!--开启controller扫描-->
<context:component-scan base-package="com.ocean.base.controller"/>
<!--配置springmvc的视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!--
自动注册最合适的处理器映射器,处理器适配器(调用handler方法)
-->
<!--<mvc:annotation-driven/>-->
</beans>
Controller
@Controller
@RequestMapping("/demo")
public class DemoController {
@RequestMapping("/handle01")
public String handle01(String name, Map<String, Object> model) {
System.out.println("++++++++handler业务逻辑处理中....");
Date date = new Date();
model.put("date", date);
return "success";
}
@RequestMapping("/index")
public ModelAndView getModeAndView() {
//创建一个模型视图对象
ModelAndView mav = new ModelAndView("index");
return mav;
}
}
mvc调用的主流程
-
DispatcherServlet
(前端控制器) 是个servlet
,负责接收Request
并将Request
转发给对应的处理组件。 -
HanlerMapping
(处理器映射器)是SpringMVC 中完成url 到Controller
映射的组件。DispatcherServlet
从HandlerMapping
查找处理Request
的Controller
, -
HanlerMapping
返回一个执行器链(url 到Controller 映射的组件)给DispatcherServlet
-
DispatcherServlet
请求处理器适配器HandlerAdapter
- 处理器适配器
HandlerAdapter
去访问我们的handler(controller)
-
handler(controller)
返回ModelAndView
给处理器适配器HandlerAdapter
- 处理器适配器
HandlerAdapter
返回ModelAndView
给DispatcherServlet
-
DispatcherServlet
请求ViewResolver
视图解析器 -
ViewResolver
视图解析器返回view给DispatcherServlet
-
DispatcherServlet
请求view做页面解析和渲染 -
view
将渲染好的数据返回给DispatcherServlet
,DispatcherServlet
将渲染好的字符流给client,看到了页面!