7.1 Spring MVC起步
7.1.1 跟踪Spring MVC的请求
在spring MVC中,DispatcherServlet是前端控制器,客户端的请求以及各种请求(处理器映射器,处理器适配器,视图解析器等返回的结果都是它转发给下一个模块)的转发都是它控制的。
1)前端发送请求;2)DispatcherServlet(前端控制器),接受请求,根据url通过处理器映射器会返回一个结果(这个结果是啥,不是很清楚);2)然后这个结果又返回给前端控制器,前端控制器根据这个结果,通过处理器适配器找到要请求的controller(通常我们写成Controller层,实际是Handler);3)controller处理业务,业务处理完之后,会返回ModelAndView(逻辑视图名,或者是数据);4)然后前端控制器将controller返回的ModelAndView转发给视图解析器;视图解析器将数据渲染成jsp页面(或者其他形式的显示页面)或者根据逻辑视图名找到物理视图;5)前端控制器根据视图解析的结果相应客户端。(传智这个讲的非常清晰,可以看看,下面补张图)
7.1.2 搭建Spring MVC
搭建springmvc之前先学会用maven+eclipse搭建一个web工程:
在web.xml中配置前端控制器DispatcherServlet:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> 3 <display-name>chapter07</display-name> 4 <welcome-file-list> 5 <welcome-file>index.html</welcome-file> 6 <welcome-file>index.htm</welcome-file> 7 <welcome-file>index.jsp</welcome-file> 8 <welcome-file>default.html</welcome-file> 9 <welcome-file>default.htm</welcome-file> 10 <welcome-file>default.jsp</welcome-file> 11 12 13 14 </welcome-file-list> 15 <!-- 配置前端控制器 --> 16 <servlet> 17 <servlet-name>spitter</servlet-name> 18 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 19 <load-on-startup>1</load-on-startup> 20 </servlet> 21 <servlet-mapping> 22 <servlet-name>spitter</servlet-name> 23 <url-pattern>/</url-pattern> 24 </servlet-mapping> 25 </web-app>
同时,在WEB-INF下创建一个spitter-servlet.xml文件,该文件主要是Spring的应用文件:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xmlns:aop="http://www.springframework.org/schema/aop" 6 xmlns:tx="http://www.springframework.org/schema/tx" 7 xmlns:p="http://www.springframework.org/schema/p" 8 xmlns:mvc="http://www.springframework.org/schema/mvc" 9 xsi:schemaLocation="http://www.springframework.org/schema/beans 10 http://www.springframework.org/schema/beans/spring-beans-4.0.xsd 11 http://www.springframework.org/schema/context 12 http://www.springframework.org/schema/context/spring-context-4.0.xsd 13 http://www.springframework.org/schema/aop 14 http://www.springframework.org/schema/aop/spring-aop-4.0.xsd 15 http://www.springframework.org/schema/tx 16 http://www.springframework.org/schema/tx/spring-tx-4.0.xsd 17 http://www.springframework.org/schema/mvc 18 http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> 19 20 <!-- 开启mvc注解驱动 --> 21 <mvc:annotation-driven/> 22 23 <!--注解形式的 组件扫描 --> 24 <context:component-scan 25 base-package="com.springinaction.*"></context:component-scan> 26 27 28 <!-- 静态文件访问的配置 --> 29 <mvc:resources location="/js/" mapping="/js/**"/> 30 <mvc:resources location="/css/" mapping="/css/**"/> 31 <mvc:resources location="/img/" mapping="/img/**"/> 32 33 </beans>
7.2 编写控制器
7.2.1 配置注解驱动的Spring MVC
Spring自带了多个处理器映射器实现供我们选择:
- BeanNameUrlHandlerMapping:根据控制器Bean的名字将控制器映射到URL
- ControllerBeanNameHandlerMapping:与BeanNameUrlHandlerMapping类似,根据空控制器Bean的名字将控制器映射到URL。使用该处理器映射实现,Bean的名字不需要遵循URL的约定。
- ControllerClassNameHandlerMapping:通过使用控制器的类名作为URL基础将控制器映射到URl
- SimpleUrlHandlerMapping:使用定义在Spring应用上线文的属性集合将控制器映射到URL。
以上均需要配置一个Bean,但是mvc有个注解驱动<mvc:annotation-driven>,可以代替处理器映射器,处理器适配器等等
7.2.2 定义首页的控制器
pom.xml文件:
1 <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/xsd/maven-4.0.0.xsd"> 2 <modelVersion>4.0.0</modelVersion> 3 <groupId>com.springinaction.chapter07</groupId> 4 <artifactId>chapter07</artifactId> 5 <version>0.0.1-SNAPSHOT</version> 6 <packaging>war</packaging> 7 <dependencies> 8 <!-- log4j的依赖 --> 9 <dependency> 10 <groupId>log4j</groupId> 11 <artifactId>log4j</artifactId> 12 <version>1.2.14</version> 13 </dependency> 14 <!-- junit的依赖 --> 15 <dependency> 16 <groupId>junit</groupId> 17 <artifactId>junit</artifactId> 18 <version>4.11</version> 19 <scope>test</scope> 20 </dependency> 21 <!-- spring beans的依赖 --> 22 <dependency> 23 <groupId>org.springframework</groupId> 24 <artifactId>spring-beans</artifactId> 25 <version>4.2.9.RELEASE</version> 26 </dependency> 27 <!-- spring context(应用上下文的依赖) --> 28 <!-- <dependency> 29 <groupId>org.springframework</groupId> 30 <artifactId>spring-context</artifactId> 31 <version>4.2.9.RELEASE</version> 32 </dependency> --> 33 <!-- JSR-330的标准注解 --> 34 <dependency> 35 <groupId>javax.inject</groupId> 36 <artifactId>javax.inject</artifactId> 37 <version>1</version> 38 </dependency> 39 <!-- spring aspects依赖,AOP用到 --> 40 <!-- <dependency> 41 <groupId>org.springframework</groupId> 42 <artifactId>spring-aspects</artifactId> 43 <version>4.2.9.RELEASE</version> 44 </dependency> --> 45 <!-- 配置数据源的链接dbcp( 提供链接池功能)--> 46 <!-- <dependency> 47 <groupId>commons-dbcp</groupId> 48 <artifactId>commons-dbcp</artifactId> 49 <version>1.3</version> 50 </dependency> --> 51 <!-- mysql的链接的驱动包 --> 52 <!-- <dependency> 53 <groupId>mysql</groupId> 54 <artifactId>mysql-connector-java</artifactId> 55 <version>5.1.40</version> 56 </dependency> --> 57 <!-- spring-jdbc配置数据源 --> 58 <!-- <dependency> 59 <groupId>org.springframework</groupId> 60 <artifactId>spring-jdbc</artifactId> 61 <version>4.2.9.RELEASE</version> 62 </dependency> --> 63 <!-- <dependency> 64 <groupId>org.springframework</groupId> 65 <artifactId>spring-jdbc</artifactId> 66 <version>3.1.0.RELEASE</version> 67 </dependency> --> 68 <!-- spring orm --> 69 <!-- <dependency> 70 <groupId>springframework</groupId> 71 <artifactId>spring-orm</artifactId> 72 <version>1.1.3</version> 73 </dependency> --> 74 <!-- spring orm --> 75 <!-- <dependency> 76 <groupId>org.springframework</groupId> 77 <artifactId>spring-orm</artifactId> 78 <version>4.2.9.RELEASE</version> 79 </dependency> --> 80 <!-- mybatis jar --> 81 <!-- <dependency> 82 <groupId>org.mybatis</groupId> 83 <artifactId>mybatis</artifactId> 84 <version>3.2.2</version> 85 </dependency> --> 86 <!-- mybatis spring jar --> 87 <!-- <dependency> 88 <groupId>org.mybatis</groupId> 89 <artifactId>mybatis-spring</artifactId> 90 <version>1.3.0</version> 91 </dependency> --> 92 <!-- spring mvc的jar包 --> 93 <dependency> 94 <groupId>org.springframework</groupId> 95 <artifactId>spring-webmvc</artifactId> 96 <version>4.2.8.RELEASE</version> 97 </dependency> 98 99 <!-- 编写测试用例用到,初次用 --> 100 <dependency> 101 <groupId>org.mockito</groupId> 102 <artifactId>mockito-all</artifactId> 103 <version>1.10.19</version> 104 </dependency> 105 106 107 </dependencies> 108 109 110 111 <build> 112 <!-- 配置插件 --> 113 <plugins> 114 <plugin> 115 <groupId>org.apache.tomcat.maven</groupId> 116 <artifactId>tomcat7-maven-plugin</artifactId> 117 <configuration> 118 <port>8080</port> 119 <path>/</path> 120 <url>localhost:8080/</url> 121 <username>tomcat</username> 122 <password>tomcat</password> 123 </configuration> 124 </plugin> 125 </plugins> 126 </build> 127 128 </project>
controller:
1 package com.springinaction.controller; 2 3 import java.util.Map; 4 5 import javax.inject.Inject; 6 7 import org.springframework.stereotype.Controller; 8 import org.springframework.web.bind.annotation.RequestMapping; 9 10 import com.springinaction.service.SpitterService; 11 12 13 @Controller 14 public class HomeController { 15 16 public static final int DEFAULT_SPITTLES_PER_PAGE = 25; 17 18 private SpitterService spitterService; 19 20 @Inject 21 public HomeController(SpitterService spitterService){ 22 this.spitterService = spitterService; 23 } 24 25 @RequestMapping({"/","/home"}) 26 public String showHomePage(Map<String,Object> model){ 27 model.put("spittles", spitterService.getRecentSpittles(DEFAULT_SPITTLES_PER_PAGE)); 28 29 return "home"; 30 } 31 32 33 }
model:
1 package com.springinaction.model; 2 3 public class Spitte { 4 5 }
service:
1 package com.springinaction.service; 2 3 public interface SpitterService { 4 5 Object getRecentSpittles(int defaultSpittlesPerPage); 6 7 }
serviceImpl:
1 package com.springinaction.service.impl; 2 3 import com.springinaction.service.SpitterService; 4 5 public class SpitterServiceImpl implements SpitterService { 6 7 @Override 8 public Object getRecentSpittles(int defaultSpittlesPerPage) { 9 10 return null; 11 } 12 13 }
测试用例:
1 package com.springinaction.test; 2 3 import static com.springinaction.controller.HomeController.*; 4 import static org.junit.Assert.*; 5 import static org.mockito.Mockito.*; 6 import static java.util.Arrays.*; 7 8 import java.util.HashMap; 9 import java.util.List; 10 11 import org.junit.After; 12 import org.junit.AfterClass; 13 import org.junit.Before; 14 import org.junit.BeforeClass; 15 import org.junit.Test; 16 17 import com.springinaction.controller.HomeController; 18 import com.springinaction.model.Spitte; 19 import com.springinaction.service.SpitterService; 20 21 public class HomeControllerTest { 22 23 @Test 24 public void test() { 25 //模拟SpitterService 26 List<Spitte> expectedSpittles = asList(new Spitte(),new Spitte(),new Spitte()); 27 SpitterService spitterService = mock(SpitterService.class); 28 29 when(spitterService.getRecentSpittles(DEFAULT_SPITTLES_PER_PAGE)) 30 .thenReturn(expectedSpittles); 31 32 //创建控制器 33 HomeController controller = new HomeController(spitterService); 34 HashMap<String, Object> model = new HashMap<String,Object>(); 35 String viewName = controller.showHomePage(model);//调用处理方 36 37 //对处理方法进行对比 38 assertEquals("home", viewName); 39 verify(spitterService).getRecentSpittles(DEFAULT_SPITTLES_PER_PAGE); 40 } 41 42 }
上面测试用例写的懵逼啊,但是测试是通过的,又涨姿势了,若是想用某个包下面的某个类的方法,import static 包名.类名.*;这样就可以了。
7.2.3 解析视图
视图解析器的工作是将逻辑视图的名字与org.springframework.web.servlet.View的实现相匹配。视图解析器就是将名称与JSP进行匹配。
解析内部视图:InternalResourceViewResolver是一个面向约定的元素。他将逻辑视图名称解析为View对象,而该对象将渲染的任务委托给Web应用程序上下文中的一个模板。
在spitter-servlet.xml配置视图解析器的bean:
1 <!-- 视图解析器 --> 2 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 3 <!-- 这个属性之前没见过,是因为home.jsp使用了一些JSTL标签, --> 4 <property name="prefix" value="/WEB-INF/views/*"></property> 5 <property name="suffix" value="/WEB-INF/.jsp"></property> 6 </bean>
这本书的下面用到了一个Tiles布局视图,看着懵逼,没工夫研究他。下面我自己根据学习的知识(传智的视频,这里只是说他视频资源非常好,没有广告的嫌疑,网上都可以下载到的资源)搭建一个从前台展示到controller的一个请求和数据回显的过程。
首先整个工程结构还是如上,
1.上面讲述一种的spitter-servlet.xml(这是书本里叫的名字,后面我重命名另外一个名字springmvc.xml)的配置,是将其放在了WEB-INF下面,这是web.xml加载spitter-servlet.xml的默认位置,而且命名必须是*-servlet.xml,还有第二种配法,是将其其位置统一放在了src/main/resources下面的文件夹下(我上面的搭建过程还自动生成了几个xml文件,自动生成的删掉或者重命名成自己需要的,如下图),maven工程项目中的大部分xml配置文件都放在这个文件夹下,在springmvc.xml文件中做与spitter-servlet.xml相同的配置,因为不用spitter-servlet配置,所以最好将之前的HomeController里的注解注释掉。
2.想连接数据库做一个查询分页的效果(并且采用jquey-EasyUi的控件尝试一下,所以),所以搞定准备工作先,
2.1数据库(mysql)里建立一张user表(id主键)
2.2将需要的mybatis依赖的jar文件,spring的jar文件等等通过pom.xml引进来,里面应该是大部分引进来了,有需要的后面再添加:
1 <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/xsd/maven-4.0.0.xsd"> 2 <modelVersion>4.0.0</modelVersion> 3 <groupId>com.springinaction.chapter07</groupId> 4 <artifactId>chapter07</artifactId> 5 <version>0.0.1-SNAPSHOT</version> 6 <packaging>war</packaging> 7 <dependencies> 8 <!-- log4j的依赖 --> 9 <dependency> 10 <groupId>log4j</groupId> 11 <artifactId>log4j</artifactId> 12 <version>1.2.14</version> 13 </dependency> 14 <!-- junit的依赖 --> 15 <dependency> 16 <groupId>junit</groupId> 17 <artifactId>junit</artifactId> 18 <version>4.11</version> 19 <scope>test</scope> 20 </dependency> 21 <!-- 引入jstl标签库的jar --> 22 <dependency> 23 <groupId>javax.servlet</groupId> 24 <artifactId>jstl</artifactId> 25 <version>1.2</version> 26 </dependency> 27 <!-- 引入tiles标签库的jar --> 28 <!-- <dependency> 29 <groupId>org.apache.tiles</groupId> 30 <artifactId>tiles-jsp</artifactId> 31 <version>2.2.2</version> 32 </dependency> --> 33 <!-- spring beans的依赖 --> 34 <dependency> 35 <groupId>org.springframework</groupId> 36 <artifactId>spring-beans</artifactId> 37 <version>4.2.9.RELEASE</version> 38 </dependency> 39 <!-- spring context(应用上下文的依赖) --> 40 <dependency> 41 <groupId>org.springframework</groupId> 42 <artifactId>spring-context</artifactId> 43 <version>4.2.9.RELEASE</version> 44 </dependency> 45 <!-- JSR-330的标准注解 --> 46 <!-- <dependency> 47 <groupId>javax.inject</groupId> 48 <artifactId>javax.inject</artifactId> 49 <version>1</version> 50 </dependency> --> 51 <!-- spring aspects依赖,AOP用到 --> 52 <dependency> 53 <groupId>org.springframework</groupId> 54 <artifactId>spring-aspects</artifactId> 55 <version>4.2.9.RELEASE</version> 56 </dependency> 57 <!-- 配置数据源的链接dbcp( 提供链接池功能)--> 58 <dependency> 59 <groupId>commons-dbcp</groupId> 60 <artifactId>commons-dbcp</artifactId> 61 <version>1.3</version> 62 </dependency> 63 <!-- mysql的链接的驱动包 --> 64 <dependency> 65 <groupId>mysql</groupId> 66 <artifactId>mysql-connector-java</artifactId> 67 <version>5.1.40</version> 68 </dependency> 69 <!-- spring-jdbc配置数据源 --> 70 <dependency> 71 <groupId>org.springframework</groupId> 72 <artifactId>spring-jdbc</artifactId> 73 <version>4.2.9.RELEASE</version> 74 </dependency> 75 <!-- <dependency> 76 <groupId>org.springframework</groupId> 77 <artifactId>spring-jdbc</artifactId> 78 <version>3.1.0.RELEASE</version> 79 </dependency> --> 80 <!-- spring orm --> 81 <!-- <dependency> 82 <groupId>springframework</groupId> 83 <artifactId>spring-orm</artifactId> 84 <version>1.1.3</version> 85 </dependency> --> 86 <!-- spring orm --> 87 <!-- <dependency> 88 <groupId>org.springframework</groupId> 89 <artifactId>spring-orm</artifactId> 90 <version>4.2.9.RELEASE</version> 91 </dependency> --> 92 <!-- mybatis jar --> 93 <dependency> 94 <groupId>org.mybatis</groupId> 95 <artifactId>mybatis</artifactId> 96 <version>3.2.2</version> 97 </dependency> 98 <!-- mybatis spring jar --> 99 <dependency> 100 <groupId>org.mybatis</groupId> 101 <artifactId>mybatis-spring</artifactId> 102 <version>1.3.0</version> 103 </dependency> 104 <!-- spring mvc的jar包 --> 105 <dependency> 106 <groupId>org.springframework</groupId> 107 <artifactId>spring-webmvc</artifactId> 108 <version>4.2.8.RELEASE</version> 109 </dependency> 110 111 <!-- 编写测试用例用到,初次用 --> 112 <dependency> 113 <groupId>org.mockito</groupId> 114 <artifactId>mockito-all</artifactId> 115 <version>1.10.19</version> 116 </dependency> 117 118 119 </dependencies> 120 121 122 123 <build> 124 <!-- 配置插件 --> 125 <plugins> 126 <plugin> 127 <groupId>org.apache.tomcat.maven</groupId> 128 <artifactId>tomcat7-maven-plugin</artifactId> 129 <configuration> 130 <port>8080</port> 131 <path>/</path> 132 <url>localhost:8080/</url> 133 <username>tomcat</username> 134 <password>tomcat</password> 135 </configuration> 136 </plugin> 137 </plugins> 138 </build> 139 140 </project>
2.3 介绍一个逆向工程的工具(有点吊,很好使)下载地址:
下面是generatorConfig.xml配置:1、配置数据库的连接信息,我的user表在test库里面,2、配置生成的po(其实就是model了,我习惯了model)类的位置,3、配置生成的mapper接口(其实就是dao层的接口)的位置,4、配置mapper映射文件的位置(mybatis主要就是写这个mapper.xml文件,但是有逆向工程了,还写个毛线),5、配数据库中要使用的表名,这几个配置好,直接运行GeneratorSqlmap.java中的main方法,就会生成了(若是没有看到,请刷新工程),如下图:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE generatorConfiguration 3 PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" 4 "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> 5 6 <generatorConfiguration> 7 <context id="testTables" targetRuntime="MyBatis3"> 8 <commentGenerator> 9 <!-- 是否去除自动生成的注释 true:是 : false:否 --> 10 <property name="suppressAllComments" value="true" /> 11 </commentGenerator> 12 <!--数据库连接的信息:驱动类、连接地址、用户名、密码 --> 13 <jdbcConnection driverClass="com.mysql.jdbc.Driver" 14 connectionURL="jdbc:mysql://localhost:3306/test" userId="root" 15 password="mysql"> 16 </jdbcConnection> 17 <!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和 18 NUMERIC 类型解析为java.math.BigDecimal --> 19 <javaTypeResolver> 20 <property name="forceBigDecimals" value="false" /> 21 </javaTypeResolver> 22 23 <!-- targetProject:生成PO类的位置 --> 24 <javaModelGenerator targetPackage="com.springinaction.model" 25 targetProject=".\src"> 26 <!-- enableSubPackages:是否让schema作为包的后缀 --> 27 <property name="enableSubPackages" value="false" /> 28 <!-- 从数据库返回的值被清理前后的空格 --> 29 <property name="trimStrings" value="true" /> 30 </javaModelGenerator> 31 <!-- targetProject:mapper映射文件生成的位置 --> 32 <sqlMapGenerator targetPackage="com.springinaction.mapper" 33 targetProject=".\src"> 34 <!-- enableSubPackages:是否让schema作为包的后缀 --> 35 <property name="enableSubPackages" value="false" /> 36 </sqlMapGenerator> 37 <!-- targetPackage:mapper接口生成的位置 --> 38 <javaClientGenerator type="XMLMAPPER" 39 targetPackage="com.springinaction.mapper" 40 targetProject=".\src"> 41 <!-- enableSubPackages:是否让schema作为包的后缀 --> 42 <property name="enableSubPackages" value="false" /> 43 </javaClientGenerator> 44 <!-- 指定数据库表 --> 45 <table schema="" tableName="user"></table> 46 47 48 </context> 49 </generatorConfiguration>
3、配置一些xml文件:
3.1配置mybatis的sqlMapConfig.xml,在src/main/resources下面,创建mybatis/sqlMapConfig.xml,里面先不配置,需要再配置:
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE configuration 3 PUBLIC "-//mybatis.org//DTD Config 3.0//EN" 4 "http://mybatis.org/dtd/mybatis-3-config.dtd"> 5 <configuration> 6 7 </configuration>
3.2在src/main/resources创建resource/db.properties的数据库连接配置文件
1 jdbc.driver=com.mysql.jdbc.Driver 2 jdbc.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf-8 3 jdbc.username=root 4 jdbc.password=mysql
3.3在spring文件夹配置dao层(即mapper接口层)的spring bean容器applicationContext-dao.xml,里面主要配置数据源,和扫描mapper接口的bean配置(这里只是扫描mapper接口,而mapper.xml却扫描不到,下面有关于这个问题的处理):
1 <beans xmlns="http://www.springframework.org/schema/beans" 2 xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" 3 xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 4 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 5 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd 6 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd 7 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd 8 http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd"> 9 10 <!-- 数据库链接池 --> 11 <!-- 加载配置文件 --> 12 <context:property-placeholder location="classpath:resource/*.properties"/> 13 <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" > 14 <property name="url" value="${jdbc.url}"></property> 15 <property name="username" value="${jdbc.username}"></property> 16 <property name="password" value="${jdbc.password}"></property> 17 <property name="driverClassName" value="${jdbc.driver}"></property> 18 <property name="initialSize" value="5"></property> 19 <property name="maxActive" value="10"></property> 20 </bean> 21 22 <!-- 配置SqlSessionFactory --> 23 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> 24 25 <property name="configLocation" value="classpath:mybatis/sqlMapConfig.xml"></property> 26 <property name="dataSource" ref="dataSource"></property> 27 </bean> 28 <!-- 配置扫描包 --> 29 <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> 30 <property name="basePackage" value="com.springinaction.mapper"></property> 31 </bean> 32 33 </beans>
3.4在spring文件夹配置service的spring bean容器applicationContext-service.xml,这里主要扫面service实现类,
1 <beans xmlns="http://www.springframework.org/schema/beans" 2 xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" 3 xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 4 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 5 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd 6 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd 7 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd 8 http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd"> 9 10 <!-- 扫描包加载Service实现类 --> 11 <context:component-scan base-package="com.springinaction.service"></context:component-scan> 12 13 </beans>
3.5在spring文件夹中配置事务的spring bean容器applicationContext-trans.xml,这里主要是配置事务管理的:
1 <beans xmlns="http://www.springframework.org/schema/beans" 2 xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" 3 xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 4 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 5 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd 6 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd 7 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd 8 http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd"> 9 10 <!-- 事务管理器 --> 11 <bean id="transactionManager" 12 class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> 13 <property name="dataSource" ref="dataSource"></property> 14 </bean> 15 16 <!-- 通知 --> 17 <tx:advice id="txAdvice" transaction-manager="transactionManager"> 18 <tx:attributes> 19 <!-- 传播行为 --> 20 <tx:method name="save*" propagation="REQUIRED"/> 21 <tx:method name="insert*" propagation="REQUIRED"/> 22 <tx:method name="add*" propagation="REQUIRED"/> 23 <tx:method name="create*" propagation="REQUIRED"/> 24 <tx:method name="delete" propagation="REQUIRED"/> 25 <tx:method name="update*" propagation="REQUIRED"/> 26 <tx:method name="find*" propagation="SUPPORTS" read-only="true"/> 27 <tx:method name="select*" propagation="SUPPORTS" read-only="true"/> 28 <tx:method name="get*" propagation="SUPPORTS" read-only="true"/> 29 </tx:attributes> 30 </tx:advice> 31 32 <!-- 切面 --> 33 <aop:config> 34 <aop:advisor advice-ref="txAdvice" 35 pointcut="execution(* com.springinaction.service.*.*(..))"/> 36 </aop:config> 37 38 39 </beans>
以上的几个配置文件其实可以直接集中配置到springmvc.xml中,不过分离后,层面更加清晰,分离之后这几个文件还要在web.xml文件中配置一项,让其加载进来:
4.配置web.xml,如下:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> 3 <display-name>chapter07</display-name> 4 <welcome-file-list> 5 <welcome-file>index.html</welcome-file> 6 <welcome-file>index.htm</welcome-file> 7 <welcome-file>index.jsp</welcome-file> 8 <welcome-file>default.html</welcome-file> 9 <welcome-file>default.htm</welcome-file> 10 <welcome-file>default.jsp</welcome-file> 11 12 13 14 </welcome-file-list> 15 <!-- 配置前端控制器 --> 16 <!-- <servlet> 17 <servlet-name>spitter</servlet-name> 18 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 19 <load-on-startup>1</load-on-startup> 20 </servlet> 21 <servlet-mapping> 22 <servlet-name>spitter</servlet-name> 23 <url-pattern>/</url-pattern> 24 </servlet-mapping> --> 25 26 <!-- 前端控制器的第二种配法 --> 27 28 <servlet> 29 <servlet-name>springmvc</servlet-name> 30 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 31 <!-- 注意这里和上面的配置不一样,若是采取第二种配置,必须配置初始化参数的位置,加载springmvc.xml--> 32 <init-param> 33 <param-name>contextConfigLocation</param-name> 34 <param-value>classpath:spring/springmvc.xml</param-value> 35 </init-param> 36 <load-on-startup>1</load-on-startup> 37 </servlet> 38 <servlet-mapping> 39 <servlet-name>springmvc</servlet-name> 40 <url-pattern>/</url-pattern> 41 </servlet-mapping> 42 43 <!-- 加载spring容器 --> 44 <context-param> 45 <param-name>contextConfigLocation</param-name> 46 <param-value>classpath:spring/applicationContext-*.xml</param-value> 47 </context-param> 48 <listener> 49 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 50 </listener> 51 </web-app>
下面maven build运行一下,可以访问到index.jsp页面,maven build在搭建maven工程里面有涉及,说明目前配置没多大问题,我们进行开发了:
首先将刚才逆向工程的文件copy进来,然后开发service、controller
UserService:
1 package com.springinaction.service; 2 3 import java.util.List; 4 5 import com.springinaction.model.User; 6 7 public interface UserService { 8 9 List<User> selectAllUser(); 10 11 }
UserServiceImpl:
1 package com.springinaction.service.impl; 2 3 import java.util.List; 4 5 import org.springframework.beans.factory.annotation.Autowired; 6 import org.springframework.stereotype.Service; 7 8 import com.springinaction.mapper.UserMapper; 9 import com.springinaction.model.User; 10 import com.springinaction.service.UserService; 11 12 @Service 13 public class UserServiceImpl implements UserService { 14 15 //mapper是逆向工程生成的,方法也是,所以直接调用里面的方法就可以 16 @Autowired 17 private UserMapper userMapper; 18 19 @Override 20 public List<User> selectAllUser() { 21 22 return userMapper.selectByExample(null); 23 } 24 25 }
UserController:
1 package com.springinaction.controller; 2 3 import java.util.List; 4 5 import org.springframework.beans.factory.annotation.Autowired; 6 import org.springframework.stereotype.Controller; 7 import org.springframework.web.bind.annotation.RequestMapping; 8 9 import com.springinaction.model.User; 10 import com.springinaction.service.UserService; 11 12 @Controller 13 public class UserController { 14 15 @Autowired 16 private UserService userService; 17 18 @RequestMapping("/user/userList") 19 public List<User> selectAllUser(){ 20 System.out.println(userService.selectAllUser()); 21 return userService.selectAllUser(); 22 } 23 24 }
然后开启服务,进行访问,报错:
上面图中说插件不准确,是在pom.xml中的<build>标签中配置一个<resources></resources>,具体如下:
1 <!-- 如果不添加此节点mybatis的mapper.xml文件都会被漏掉 --> 2 <resources> 3 <!-- 坑就在这里,视频里就配置第一个resource 4 他的目的是把src/main/java/**下面的所有的properties、xml文件拷贝到 5 \chapter07\target\classes\com\springinaction\下面对应的文件夹中, 6 --> 7 <resource> 8 <directory>src/main/java</directory> 9 <includes> 10 <include>**/*.properties</include> 11 <include>**/*.xml</include> 12 </includes> 13 <filtering>false</filtering> 14 </resource> 15 <!-- 我只配了上面那个就报错了,所示找不到spring/文件夹下的spring bean容器文件, 16 结果我查看\chapter07\target\classes\,确实是哪些文件没有被拷贝进来,于是上面的写法 17 配置了如下的resource,他就把src/main/resources文件下的哪些配置文件拷贝到\chapter07\target\classes\下面了 18 --> 19 <resource> 20 <directory>src/main/resources</directory> 21 <includes> 22 <include>**/*.properties</include> 23 <include>**/*.xml</include> 24 </includes> 25 <filtering>false</filtering> 26 </resource> 27 </resources> 28
这时候访问路径localhost:8080/user/userList,由于没有jsp页面所以报错,但是控制台打印出了从数据库拿到的数据:
下一篇:第7章 使用Spring MVC构建Web程序(二),前端用jquery-EasyUi显示,运用分页插件,进行分页处理。