SpringMVC 工作流程
- 启动阶段
- 加载web.xml中DispatcherServlet
- 读取spring-mvc.xml中的配置,加载所有com.example包中所有标记为bean的类
- 读取bean中方法上标注 @RequestMapping 的内容
- 处理请求
- DispatcherServlet配置拦截所有请求 /
- 使用请求与所加载的 @ResquestMapping 的内容进行对比
- 执行对应的方法
- 根据方法的返回值在 webapp 目录中查找对应的页面并展示
SpringMVC 组件说明
- DispatcherServlet: 前端控制器,整体流程控制的中心,调用其他组件处理用户的请求,降低组件间的耦合性
- HandlerMapping: 处理映射器,根据用户请求匹配Handle处理器
- Handler: 处理器,业务处理的核心类(Controller层)
- HandlerAdapter: 处理适配器,执行处理器
- ModelAndView: SpringMVC的封装对象
- ViewResolver: 视图解析器,将处理结果生成View视图
- View: SpringMVC的封装对象
开发流程
1. 全注解模式
2. 配置加注解
配置
- 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 xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<display-name>Archetype Created Web Application</display-name>
<!--过滤器解决中文乱码问题-->
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--配置前端控制器-->
<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:spring-mvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
- spring-mvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--扫描controller层-->
<context:component-scan base-package="com.example.controller"/>
<!--使用SpringMVC的默认静态资源放行-->
<mvc:default-servlet-handler/>
<!--SpringMVC注解驱动-->
<mvc:annotation-driven/>
<!--配置作为登录验证的拦截器-->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/admin/*" />
<bean class="com.example.controller.interceptor.AdminAuthorityInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
</beans>
注解
@Controller:controller层