One, SpringMVC overview and request processing flow
1. Introduction to SpringMVC
- SpringMVC is a framework based on Spring, which is actually a module of Spring, specially used for web development.
- The bottom layer of web development is servlet, and one of the objects in springmvc is Servlet: DispatherServlet (central dispatcher)
DispatherServlet: Responsible for receiving all requests from the user, the user sends the request to DispatherServlet, then DispatherServlet forwards the request to our Controller object, and finally Controller The object handles the request. - Spring is a container, ioc can manage objects, using <bean>, @Component, @Repository, @Service, @Controller, SpringMVC can create objects and put them in the container (SpringMVC container), and the controller object is placed in the SpringMVC container What we have to do is to use @Contorller to create a controller object, put the object into the SpringMVC container, and use the created object as a controller. This controller object can receive the user's request, display the processing result, and use it as a servlet. The @Controller annotation is used to create an object of an ordinary class, not a Servlet. SpringMVC gives the controller object some additional functions.
2. The first annotated SpringMVC program
- The so-called annotation-based development of SpringMVC means that the registration of the processor in the SpringMVC container can be completed by annotating classes and methods in the code
(1) Add dependencies and plug-ins in the pom.xml file
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
</dependencies>
<build>
<plugins>
<!-- 编码和编译和JDK版本 -->
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
(2) Register the central scheduler in the web.xml file
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
A、< load-on-startup/ >
The effect of adding <load-on-startup/> in <servlet/> is to mark whether this servlet instance will be created when the Web server (here, Tomcat) starts, that is, whether to call the init of the Servlet when the Web server starts () method instead of being created when it is actually accessed. Its value must be an integer.
➢ When the value is greater than or equal to 0, it means that the container loads and initializes the servlet when it starts. The smaller the value, the
higher the priority of the servlet and the earlier it is created;
➢ When the value is less than 0 or not specified When, it means that the servlet will be created only when it is actually used.
➢ When the values are the same, the container will choose the creation order by itself.
B、< url-pattern/ >
Two values can be used:
1. Use the extension method, syntax: *.xxx, xxx is a custom extension. Commonly used methods *. html, *.do, etc.
http://localhost:8080/springmvc/add.html
http://localhost:8080/springmvc/index.html
2. Use diagonal pole method, "/"
(3) Location and name of configuration file
- After the central scheduler is registered, it can be published and run directly on the server. At this time, when accessing the browser page, the console will throw FileNotFoundException. That is, by default, the configuration file named Servlet name-servlet.xml is to be found under the WEB-INF directory under the project root. The "Servlet name" here refers to the name value of the Servlet specified in the tag of the registered central dispatcher. The configuration file name in this example is springmvc-servlet.xml.
- In general, the configuration file is placed in the classpath, that is, under the resources directory. Therefore, when registering the central
scheduler, you also need to set the path and file name of the SpringMVC configuration file for the central scheduler.
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<!--自定义springmvc读取配置文件的位置-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
(4) Create a processor
- Just add corresponding annotations on the class and method.
- @Controller: Indicates that the current class is a processor
- @RequestMapping: Indicates that the current method is a processor method. This method needs to process and respond to the URI specified by the value attribute. The method name of the annotated method can be arbitrary.
@Controller
public class MyController {
/**
* 处理用户提交的请求,springmvc中是使用方法来处理的
* 方法是自定义的,可以有多种返回值
*/
/**
* @RequestMapping:请求映射,作用是把一个请求地址和一个方法绑定在一起
* 一个请求指定一个方法处理
* 属性:
* 1、value是一个String类型的,表示请求的地址(addUser.html)
*
* 说明:使用RequestMapping修饰的方法叫做处理器方法或者控制器方法,
* 它作用类似Servlet中的doGet(),doPost()方法
*
* 返回值:ModelAndView,表示请求的处理结果
* Model:请求处理完显示给用户的数据
* View:视图,比如jsp等等
*/
@RequestMapping(value = "/addUser.do")
public ModelAndView addUser(){
//该方法addUser.html的请求,这里不在调用service请求处理了,
// 直接相当于service调用处理完成了
ModelAndView mv = new ModelAndView();
//添加数据
//框架在请求的最后把数据放入到request作用域中
//request.setAttribute("zs","张三");
mv.addObject("zs","张三");
mv.addObject("lisi","李四");
//指定视图的完整路径
//框架对视图执行的转发操作
//request.getRequestDispather("/jsp/show.jsp").forward(request,response);
//mv.setViewName("/jsp/show.jsp");
//mv.setViewName("/WEB-INF/jsp/show.jsp");
//当配置了视图解析器
//框架会使用视图解析器的(前缀+文件名+后缀)组成完整路径
// /WEB-INF/jsp/+show+.jsp
mv.setViewName("show");
//返回视图
return mv;
}
@RequestMapping(value = {
"/remove.html","/remove1.html"})
public ModelAndView removeUser(){
ModelAndView mv = new ModelAndView();
mv.addObject("zs","删除张三");
mv.addObject("lisi","删除李四");
mv.setViewName("show");
return mv;
}
}
1. If there are multiple request paths that can match the execution of the handler method, an array can be written in the value attribute of @RequestMapping.
2. The addObject() method in the ModelAndView class is used to add data to its Model. The bottom layer of the Model is a HashMap.
3. The data in the Model is stored in the scope of the request. SringMVC uses forwarding to jump to the view by default. The data in the model is destroyed when the request is over.
(5) Create SpringMVC configuration file
<!--声明组件扫描器-->
<context:component-scan base-package="com.hcz.controller"/>
(6) Define the target page
- Create a new subdirectory jsp under the webapp directory, and create a jsp page show.jsp in it.
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>显示页面</title>
</head>
<body>
<h3>显示用户姓名</h3><br>
<p>姓名:${zs}</p><br>
<p>姓名:${lisi}</p>
</body>
</html>
(7) Modify the SpringMVC configuration file
- In order to avoid redundancy on the request resource path and extension, the SpringMVC framework
introduces the prefix and suffix of the request in the view resolver InternalResouceViewResolver. In ModelAndView, you only need to give the file name of the page you want to jump to. For the specific file path and file extension, the view parser will automatically complete the splicing.
<!--声明视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--前缀:视图文件路径-->
<property name="prefix" value="/WEB-INF/jsp/"/>
<!--后缀:视图文件扩展名-->
<property name="suffix" value=".jsp"/>
</bean>
3. Use SpringMVC framework web request processing sequence
- (1) The user initiates an addUser.do request
- (2) The Tomcat server passes the url-pattern of the DispatcherServlet in the web.xml configuration file to the file with the suffix .do to the DispatcherServlet
- (3) DispatcherServlet knows @RequestMapping (value="addUser.do") according to the spring.xml configuration file component scanner
- (4) DispatcherServlet forwards addUser.do to the addUser() method of MyController for processing
- (5) The framework executes the addUser() method to process the obtained ModelAndView and forwards it to show.jsp
The following figure is a sequence diagram of the request processing:
MVC component diagram of SpringMVC:
4. SpringMVC execution flow chart
Process analysis:
(1) The browser initiates a request some.do to the central dispatcher DispatcherServlet
(2) DispatcherServlet receives the request some.so, and passes the request to the processor mapper.
Processor mapper : an object in the springmvc framework. The framework calls all classes that implement the HandlerMapping interface a mapper (multiple)
processor mappings. The role of the processor: According to the request, the processor object is obtained from the springmvc container object
MyController controller = ctx.getBean("some.do"); the
framework puts the found processor object into a processor execution chain (HandlerExecutionChain) class stored
HandlerExecutionChain : class holds
1) the object processor (MyController by)
2) All interceptors project List <HandlerInterceptor>
(3) DispatcherServlet handed over the processor object in HandlerExceptionChain in (2) to the processor adapter object (multiple).
Processor adapter : objects in the springmvc framework, need to implement the HandlerAdapt interface. The
role of the processor adapter : execute the processor method (Call MyController.doSome() to get the return value ModelAndView)
(4) DispatcherServlet passes the ModelAndView obtained in (3) to the view resolver object
view resolver : the object in the springmvc framework needs to be handed over to the ViewResoler interface (multiple)
view resolver Role : compose the full path of the view, use the prefix and Suffix, and create the view object
InternalResourceView: view class, representing the jsp file, the view parser will create the InternalResourceView object, this object has an attribute url=/WEB-INF/view/show.jsp
(5) DispatcherServlet obtains the View object created in (4), calls its own method of the View class, puts the Model data into the request scope, executes the object view forward, and the request ends.
5. Source code analysis of SpringMVC execution process
(1) The process of creating a container
A. Create a DisaptcherServlet object by specifying 1 in the load-on-start tag
B. DisaptcherServlet, whose parent class inherits HttpServlet, is a serlvet. When it is created, it executes the init() method.
C. In the init() method, create a container and read the configuration file
WebApplicationContext ctx = new ClassPathXmlApplicationContext("springmvc.xml");
D. Put the container object into the ServletContext
getServletContext().setAttribute(key, ctx);
E. After creating the container, create the object of the class where the @controller annotation is located, create the MyController object, and put this object into the springmvc container. The container is map, similar to map.put("myController", MyController object)
(2) Request processing process
1) Execute the service() of the servlet
protected void service(HttpServletRequest request, HttpServletResponse response)
protected void doService(HttpServletRequest request, HttpServletResponse response)
DispatcherServlet.doDispatch(request, response){
调用MyController的.addUser( )方法
}
doDispatch : The core method of DispatcherServlet in springmvc. All requests are completed in this method.