SpringMVC03 执行原理

1、执行流程

  • 一个请求进来之后,前置控制器 DispatcherServlet 会接收并拦截请求
    <servlet>
        <servlet-name>springmvcservlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
        <init-param>
            <param-name>contextConfigLocationparam-name>
            <param-value>classpath:spring-servlet.xmlparam-value>
        init-param>
        <load-on-startup>1load-on-startup>
    servlet>
    <servlet-mapping>
        <servlet-name>springmvcservlet-name>
        // 匹配所有的请求,不包括jsp页面,/*会包括jsp页面
        <url-pattern>/url-pattern>
    servlet-mapping>
  • DispatcherServlet 拦截请求后会调用处理器映射器 HandlerMapping,HandlerMapping 根据请求的 url 查找Handle,比如请求的url:http://127.0.0.1:8080/hello ,根据 /hello 查找映射 Handler,并返回一个执行链 HandlerExecutionChain 给DispatcherServlet
    
    <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
    
        
    <bean id="/hello" class="com.study.controller.HelloController"/>
  • DispatcherServlet 会调用处理器适配器 HandlerAdapter,HandlerAdapter 按照特定的规则找到Handler,Handler 让具体的Controller 执行,最终返回 ModelAndView 给 HandlerAdapter,HandlerAdapter 再返回给 DispatcherServlet
    
    <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>
public class HelloController implements Controller {
    public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("msg","hello mvc!");
        modelAndView.setViewName("hello");
        return modelAndView;
    }
}
  • DispatcherServlet 调用视图解析器 ViewResolver 解析ModelAndView,说白了就是解析视图名,ViewResolver 解析拼接好之后,返回给DispatcherServlet
    
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    bean>
  • DispatcherServlet 根据视图解析器解析的视图结果,调用具体的视图,最终返回给用户

2、执行图
SpringMVC03 执行原理_第1张图片

你可能感兴趣的:(Spring全家桶)