(一)SpringMVC请求原理
客户端发送request请求—>到前端控制器(DispatherServlet)---->处理器映射器(HandlerMapping)找某类中某方法取执行 —>返回到前端控制器—>处理器适配器执行---->返回ModelAndView页面到前端控制器---->请求进行视图解析器(跳转到某界面)---->根据返回结果跳转到某界面---->前端控制器发送response响应给–>客户
用到了适配器的设计模式,无论是访问什么类,都会经过适配器进行适配,然后执行最终的方法
springMVC框架基于组件方式的执行流程图如下:
组件介绍
前端控制器(DispatherServlet):它相当于mvc模式中的C,是整个流程的控制中心,有它调用其他组件处理用户的请求,它的存在降低了组件之间的耦合性
处理器映射器(HandlerMapping):根据用户请求找到Handler处理器(某方法),
处理器(Handler):他是开发中要编写的具体业务控制器。
处理器适配器(HandlerAdapter):对处理器进行执行,通过扩展适配器可以对更多类型的处理器进行执行。
视图解析器(View Resolver):跳转到某页面
视图(View):对页面进行渲染
(二)入门程序
1.控制类
//控制器
@Controller
public class HelloController {
@RequestMapping(path = "/hello")
public String sayHello(){
System.out.println("hello SpringMVC");
return "success";
}
}
2.springmvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--开启注解扫描-->
<context:component-scan base-package="com.selan"></context:component-scan>
<!--视图解析器-->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/page/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!--开启SringMVC框架注解的支持-->
<mvc:annotation-driven/>
</beans>
3.web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>dispatcher</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-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
4.index.jsp和sucess.jsp
<body>
<h3>入门程序</h3>
<%--相对路径的写法--%>
<a href="hello">入门层序</a>
</body>
<body>
<h1>入门成功</h1>
</body>
5.程序的请求执行过程