一.创建基本SpringMVC项目
1.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> <filter> <filter-name>encodingFilter</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> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <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*:/spring-mvc*.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> <welcome-file-list> <welcome-file>/index.html</welcome-file> </welcome-file-list> </web-app>
2.pom.xml配置
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.myproject</groupId> <artifactId>myproject</artifactId> <packaging>war</packaging> <version>1.0</version> <name>com.myproject Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <spring.version>4.1.6.RELEASE</spring.version> <mybatis.version>3.2.8</mybatis.version> <mybatis-spring.version>1.2.2</mybatis-spring.version> <druid.version>1.0.13</druid.version> <fastjson.version>1.2.4</fastjson.version> <jackson.version>2.2.3</jackson.version> <commons-io.version>2.4</commons-io.version> <commons-fileupload.version>1.3.1</commons-fileupload.version> </properties> <dependencies> <!-- spring 包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> <scope>test</scope> </dependency> <!-- mybatis 包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>${mybatis-spring.version}</version> </dependency> <!-- mysql连接 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.34</version> </dependency> <!-- 数据源 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>${druid.version}</version> </dependency> <!-- AOP --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.4</version> </dependency> <!-- jackson json --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${jackson.version}</version> </dependency> </dependencies> </project>
3.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-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <!-- 启用Spring注解 --> <mvc:annotation-driven />
<!-- Spring扫描器 --> <context:component-scan base-package="com.myproject" /> <!-- 对静态资源文件的访问 --> <mvc:default-servlet-handler /> <!-- Jackson转换器 --> <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" /> <!-- Mybatis配置 --> <import resource="mybatis-config.xml" /> <!-- 数据库接连参数 --> <context:property-placeholder location="classpath:mybatis.properties" /> </beans>
4.mybatis-config.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:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd "> <!-- 配置数据源 使用的是Druid数据源 --> <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <!-- 初始化连接大小 --> <property name="initialSize" value="0" /> <!-- 连接池最大使用连接数量 --> <property name="maxActive" value="20" /> <!-- 连接池最小空闲 --> <property name="minIdle" value="0" /> <!-- 获取连接最大等待时间 --> <property name="maxWait" value="60000" /> <property name="poolPreparedStatements" value="true" /> <property name="maxPoolPreparedStatementPerConnectionSize" value="33" /> <!-- 用来检测有效sql --> <property name="validationQuery" value="${validationQuery}" /> <property name="testOnBorrow" value="false" /> <property name="testOnReturn" value="false" /> <property name="testWhileIdle" value="true" /> <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 --> <property name="timeBetweenEvictionRunsMillis" value="60000" /> <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 --> <property name="minEvictableIdleTimeMillis" value="25200000" /> <!-- 打开removeAbandoned功能 --> <property name="removeAbandoned" value="true" /> <!-- 1800秒,也就是30分钟 --> <property name="removeAbandonedTimeout" value="1800" /> <!-- 关闭abanded连接时输出错误日志 --> <property name="logAbandoned" value="true" /> <!-- 监控数据库 --> <property name="filters" value="mergeStat" /> </bean> <!-- MyBatis的xml文件 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="mapperLocations" value="classpath:/mappings/**/*.xml" /> </bean> <!-- 扫描basePackage配置包下的所有接口,创建各自接口的动态代理类 --> <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.myproject" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> </bean> <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!-- 注解方式配置事物 --> <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" /> <!-- 拦截器方式配置事物 --> <tx:advice id="transactionAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="insert" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="delete*" propagation="REQUIRED" /> <tx:method name="query" propagation="SUPPORTS" /> <tx:method name="find*" propagation="SUPPORTS" /> <tx:method name="search*" propagation="SUPPORTS" /> <tx:method name="*" propagation="SUPPORTS" /> </tx:attributes> </tx:advice> <!-- Spring aop事务管理 --> <aop:config> <aop:pointcut id="transactionPointcut" expression="execution(* com.myproject.*.service.*.*(..))" /> <aop:advisor pointcut-ref="transactionPointcut" advice-ref="transactionAdvice" /> </aop:config> </beans>
5.mybatis.properties配置
#============================# #===== Database sttings =====# #============================# #oracle database settings #jdbc.type=oracle #jdbc.driver=oracle.jdbc.driver.OracleDriver #jdbc.url=jdbc:oracle:thin:@127.0.0.1:1521:orcl #jdbc.username=root #jdbc.password=123456 #mysql database setting validationQuery=SELECT 1 jdbc.type=mysql jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://127.0.0.1:3306/mysql?useUnicode=true&characterEncoding=utf-8 jdbc.username=root jdbc.password=123456
配置完成,项目看起来是这样的:
运行测试主页index.html:
测试SpringMVC:
二.SpringMVC工作原理
A.程序启动:
1.springMVC的入口是DispatcherServlet,他继承的关系是:DispatcherServlet→FrameworkServlet→HttpServletBean→HttpServlet→GenericServlet(实现Servlet)。
2.所以程序启动时会执行DispatcherServlet的init(),因为DispatcherServlet没有重写init(),所以按继承顺序往上找,找到了HttpServletBean的init()调用它;
3.init()初始化在web.xml配置DispatcherServlet时的init-param等参数,然后调用initServletBean()方法;
4.FrameworkServlet重写了initServletBean(),因为是被子类调用,所以会执行子类FrameworkServlet的initServletBean();
5.initServletBean()调用了initWebApplicationContext(),这个方法初始化子上下文,然后调用onRefresh(ApplicationContext context)方法;
6.同样,它的子类DispatcherServlet重写了onRefresh(ApplicationContext context),所以执行子类的方法;
7.DispatcherServlet又在onRefresh中调用initStrategies(ApplicationContext context),如图:
initMultipartResolver(context); //文件上传解析,如果请求类型是multipart将通过MultipartResolver进行文件上传解析;
initLocaleResolver(context); //本地化解析
initThemeResolver(context);//主题解析
initHandlerMappings(context); //通过HandlerMapping,将请求映射到处理器
initHandlerAdapters(context); //通过HandlerAdapter支持多种类型的处理器
initHandlerExceptionResolvers(context); //如果执行过程中遇到异常将交给HandlerExceptionResolver来解析
initRequestToViewNameTranslator(context); //直接解析请求到视图名
initViewResolvers(context); //通过ViewResolver解析逻辑视图名到具体视图实现
initFlashMapManager(context); //flash映射管理器
B.处理请求
1.DispatcherServlet拦截用户的请求到HttpServlet的doGet、doPost、doPut、doDelete等方法;
2.其中一个子类FrameworkServlet重写了doGet、doPost、doPut、doDelete等方法,然后调用processRequest;
3.在processRequest调用了doService方法,子类DispatcherServlet重写了doService;
4.最终调到了doService的doDispatch方法。
doDispatch遍历handlerMappings,找到第一个能处理当前请求的HandlerMapping处理器;
然后继续遍历handlerAdapters,同样找到第一个能用的HandlerAdapter适配器;
接着调用所有和当前请求相关的拦截器的前置方法;
再实际调用处理程序;
最后调用所有和当前请求相关的拦截器的后置方法。