天天看点

spring mvc流程_Spring MVC请求处理流程分析

一、简介

Spring MVC框架在工作中经常用到,配置简单,使用起来也很方便,很多书籍和博客都有介绍其处理流程,但是,对于其原理,总是似懂非懂的样子。我们做技术,需要做到知其然,还要知其所以然。今天我们结合源码来深入了解一下Spring MVC的处理流程。

spring mvc流程_Spring MVC请求处理流程分析

以上流程图是Spring MVC的处理流程(参考:spring-mvc-flow-with-example),原作者对流程的解释如下:

Step 1: First request will be received by DispatcherServlet.Step 2: DispatcherServlet will take the help of HandlerMapping and get to know the Controller class name associated with the given request.Step 3: So request transfer to the Controller, and then controller will process the request by executing appropriate methods and returns ModelAndView object (contains Model data and View name) back to the DispatcherServlet.Step 4: Now DispatcherServlet send the model object to the ViewResolver to get the actual view page.Step 5: Finally DispatcherServlet will pass the Model object to the View page to display the result.
           

针对以上流程,这里需要更加详细一点:

1、请求被web 容器接收,并且根据contextPath将请求发送给DispatcherServlet

2、DispatcherServlet接收到请求后,会设置一些属性(localeResolver、themeResolver等等),在根据request在handlerMappings中查找对应的HandlerExecutionChain;然后根据HandlerExecutionChain中的handler来找到HandlerAdapter,然后通过反射来调用handler中的对应方法(RequestMapping对应的方法)

3、handler就是对应的controller,调用controller中的对应方法来进行业务逻辑处理,返回ModelAndView(或者逻辑视图名称)

4、ViewResolver根据逻辑视图名称、视图前后缀,来获取实际的逻辑视图

5、获取实际视图之后,就会使用model来渲染视图,得到用户实际看到的视图,然后返回给客户端。

二、Demo样例

我们运行一个小样例(github地址:https://github.com/yangjianzhou/spring-mvc-demo)来了解Spring MVC处理流程,项目结构如下:

spring mvc流程_Spring MVC请求处理流程分析

web.xml配置如下:

<?xml version="1.0" encoding="UTF-8"?>contextConfigLocationclasspath:/applicationContext.xmlorg.springframework.web.context.ContextLoaderListenersmartorg.springframework.web.servlet.DispatcherServlet1smart/index.jsp
           

smart-servlet.xml的内容如下:

UserController.java的代码如下:

package com.iwill.mvc;import org.apache.log4j.Logger;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.servlet.ModelAndView;@[email protected]("/user")public class UserController { Logger logger = Logger.getLogger(UserController.class); @RequestMapping("register") public String register() { logger.info("invoke register"); return "user/register"; } @RequestMapping(method = RequestMethod.POST) public ModelAndView createUser(User user) { ModelAndView mav = new ModelAndView(); mav.setViewName("user/createSuccess"); mav.addObject("user
           

继续阅读