springMVC1. 执行流程(新手学习)
一、启动服务器,加载一些配置文件
1.DispatcherServlet对象被创建
在web.xml中配置前端控制器(就是个servlet)
<servlet> <servlet-name>dispatcherServlet</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>1</load-on-startup>
</servlet>
<!--servlet的访问路径-->
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
原先需要第一次发送请求的时候,配置的servlet才会被创建成对象。现在,由于配置了<load-on-startup>标签,直接在启动服务器的时候配置的servlet就会被创建成对象。
2.springMVC.xml配置文件被加载
由于在<init-param>中配置了contextConfigLocation,相应的classpath:springMVC.xml(类路径下的xml文件)就会被加载
springMVC.xml中的内容:
<context:component-scan base-package="com.mno2"/>
<!--视图解析器--> <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/pages/"/> <property name="suffix" value=".jsp"/> </bean> <!--开启SpringMVC框架注解的支持--> <mvc:annotation-driven/>
<context:component-scan base-package="com.mno2"/>用于开启注解扫描,在com.mno2包下的所有java类中的注解都会被扫描。
视图解析器InternalResourceViewResolver这个类也会直接bean成对象,谁调用视图解析器就可以直接完成跳转工作。
<mvc:annotation-driven/>可以让springMVC的注解生效比如:@RequestMapping(path="/hello/hello")
3.com.mno2包下的相应HelloController创建成bean对象加载到ioc容器中(默认是单例的)
package com.mno2.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; //控制器的类,接受请求 @Controller public class HelloController { @RequestMapping(path = "/hello/hello") public String sayHello(){ System.out.println("hello springMVC"); return "success"; } }
二、发送请求,后台处理请求
index.jsp中的代码:
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <h3>入门程序</h3> <a href="hello/hello">入门程序</a> </body> </html>
由于在web.xml中配置了DispatcherServlet设置了路径为/,所以所有的访问虚拟目录下的请求都会执行DispatcherServlet(前端控制器,控制作用指挥中心),DispatcherServlet会让@RequestMapping的方法执行,同时DispatcherServlet还会找到InternalResourceViewResolver(视图解析器对象),InternalResourceViewResolver会让其跳转到success.jsp页面。

浙公网安备 33010602011771号