欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Spring MVC 的 XML 配置方式

程序员文章站 2022-07-10 13:14:52
索引: 开源Spring解决方案--lm.solution 参看代码 GitHub: solution/pom.xml solution/webapi/pom.xml solution/mapper/pom.xml web.xml spring-mvc.xml spring-context.xml ......

索引:

开源Spring解决方案--lm.solution

参看代码 GitHub:

solution/pom.xml

solution/webapi/pom.xml

solution/mapper/pom.xml

web.xml

spring-mvc.xml

spring-context.xml

dbconfig.properties

log4j.properties

RESTfulController.java

一、要点讲解

  1.引入构建 spring 、spring mvc 的框架类库

  spring-context:因依赖 会自动引入 spring-aop spring-beans spring-core spring-expression 四个包

  spring-context-support

  spring-aspects

  spring-tx

  jackson-annotations:Jackson 用来解析数据,如json 或者 httpmessage 等

  jackson-databind

  jackson-core

  jackson-dataformat-xml  

  mybatis-spring:为了在spring中使用 mybatis orm 的 bean 

  mybatis

  mysql-connector-java:链接mysql数据库的驱动

  druid:数据库链接池  

  2.在Tomcat中启动 Web 的必要配置

  web-app:使用 servlet 3.0 的配置

  context-param:上下文环境配置

  listener:监听配置

  servlet:核心 servlet 配置,决定了 spring MVC 框架的启用

  3.Spring 、Spring MVC 运行相关必要配置

  mvc:annotation-driven:

    启用spring mvc 注解, 默认的注解映射的支持

    自动注册 RequestMappingHandlerMapping RequestMappingHandlerAdapter 两个 bean,这是 Spring mvc 分发请求所必须的

    并提供了数据绑定支持:读写XML支持、读写Json支持

  mvc:default-servlet-handler:

    对静态资源文件的访问,

    将无法mapping到Controller的path 交给default servlet handler处理

  context:annotation-config:

    开启注解处理器

  context:component-scan:

    自动扫描包,注册 @Controller @Service @Repository @Component 等注解的类成为 bean

二、详细使用及代码

  1.solution/pom.xml

  1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  3     <modelVersion>4.0.0</modelVersion>
  4 
  5     <groupId>lm.solution</groupId>
  6     <artifactId>solution</artifactId>
  7     <version>1.0-SNAPSHOT</version>
  8     <modules>
  9         <module>webapi</module>
 10         <module>web</module>
 11         <module>common</module>
 12         <module>service</module>
 13         <module>mapper</module>
 14         <module>pojo</module>
 15         <module>console</module>
 16         <module>webservice</module>
 17     </modules>
 18     <packaging>pom</packaging>
 19 
 20     <name>solution</name>
 21     <url>http://maven.apache.org</url>
 22 
 23     <properties>
 24         <!--编译字符集-->
 25         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 26         <!-- spring -->
 27         <spring.version>4.3.13.RELEASE</spring.version>
 28         <!-- log4j -->
 29         <slf4j.version>1.7.7</slf4j.version>
 30         <log4j.version>1.2.17</log4j.version>
 31         <!-- jackson -->
 32         <jackson.version>2.9.4</jackson.version>
 33         <!-- junit -->
 34         <junit.version>4.12</junit.version>
 35         <!-- aspectj -->
 36         <aspectj.version>1.8.13</aspectj.version>
 37         <!-- cglib -->
 38         <cglib.version>3.1</cglib.version>
 39         <!-- mybatis -->
 40         <mybatis.version>3.4.5</mybatis.version>
 41         <!-- mybatis-spring -->
 42         <mybatisSpring.version>1.3.1</mybatisSpring.version>
 43         <!--mysql-connector-->
 44         <mysql.version>5.1.34</mysql.version>
 45         <!--druid-->
 46         <druid.version>1.0.5</druid.version>
 47         <!--javax.servlet-->
 48         <javaxServlet.version>3.0.1</javaxServlet.version>
 49         <!--jsp-api-->
 50         <jspApi.version>2.2</jspApi.version>
 51         <!--jstl-->
 52         <jstl.version>1.2</jstl.version>
 53         <!--json-lib-->
 54         <jsonLib.version>2.1</jsonLib.version>
 55         <!--jackson old-->
 56         <jacksonOld.version>1.9.13</jacksonOld.version>
 57         <!--dom4j-->
 58         <dom4j.version>1.6.1</dom4j.version>
 59         <!--ehcache core-->
 60         <ehcacheCore.version>2.6.9</ehcacheCore.version>
 61         <!--ehcache web-->
 62         <ehcacheWeb.version>2.0.4</ehcacheWeb.version>
 63         <!--commons-fileupload-->
 64         <commonsFileupload.version>1.3.1</commonsFileupload.version>
 65         <!--commons-io-->
 66         <commonsIo.version>2.4</commonsIo.version>
 67         <!--commons-codec-->
 68         <commonsCodec.version>1.9</commonsCodec.version>
 69         <!--commons-collections4-->
 70         <commonsCollections4.version>4.0</commonsCollections4.version>
 71         <!--commons-beanutils-->
 72         <commonsBeanutils.version>1.7.0</commonsBeanutils.version>
 73         <!--freemarker-->
 74         <freemarker.version>2.3.19</freemarker.version>
 75         <!-- poi  poi-ooxml -->
 76         <poi.version>3.9</poi.version>
 77         <!--org.apache.httpcomponents-->
 78         <httpcore.version>4.4.8</httpcore.version>
 79         <httpclient.version>4.5.4</httpclient.version>
 80         <!-- jaxws-rt -->
 81         <jaxwsRt.version>2.3.0</jaxwsRt.version>
 82         <!-- jedis -->
 83         <jedis.version>2.9.0</jedis.version>
 84         <!-- rabbitmq -->
 85         <amqpClient.version>5.1.2</amqpClient.version>
 86         <!--fastjson-->
 87         <fastjson.version>1.2.46</fastjson.version>
 88         <!-- jsr250 -->
 89         <jsr250.version>1.0</jsr250.version>
 90     </properties>
 91 
 92     <dependencies>
 93         <!--单元测试依赖 -->
 94         <dependency>
 95             <groupId>junit</groupId>
 96             <artifactId>junit</artifactId>
 97             <version>RELEASE</version>
 98             <!--test 说明这个包的存活是在test周期,也就是发布时将不包含这个jar包-->
 99             <scope>test</scope>
100         </dependency>
101         <!--spring单元测试依赖 -->
102         <dependency>
103             <groupId>org.springframework</groupId>
104             <artifactId>spring-test</artifactId>
105             <version>${spring.version}</version>
106             <scope>test</scope>
107         </dependency>
108         <!-- spring -->
109         <dependency>
110             <groupId>org.springframework</groupId>
111             <!-- 因依赖 会自动引入 spring-aop spring-beans spring-core spring-expression 四个包 -->
112             <artifactId>spring-context</artifactId>
113             <version>${spring.version}</version>
114         </dependency>
115         <dependency>
116             <groupId>org.springframework</groupId>
117             <artifactId>spring-context-support</artifactId>
118             <version>${spring.version}</version>
119         </dependency>
120         <dependency>
121             <groupId>org.springframework</groupId>
122             <artifactId>spring-aspects</artifactId>
123             <version>${spring.version}</version>
124         </dependency>
125         <dependency>
126             <groupId>org.springframework</groupId>
127             <artifactId>spring-tx</artifactId>
128             <version>${spring.version}</version>
129         </dependency>
130         <dependency>
131             <groupId>org.springframework</groupId>
132             <artifactId>spring-jdbc</artifactId>
133             <version>${spring.version}</version>
134         </dependency>
135         <!-- aspectj AOP -->
136         <dependency>
137             <groupId>org.aspectj</groupId>
138             <artifactId>aspectjrt</artifactId>
139             <version>${aspectj.version}</version>
140         </dependency>
141         <dependency>
142             <groupId>org.aspectj</groupId>
143             <artifactId>aspectjweaver</artifactId>
144             <version>${aspectj.version}</version>
145         </dependency>
146         <!-- 映入JSON jackson -->
147         <dependency>
148             <groupId>com.fasterxml.jackson.core</groupId>
149             <artifactId>jackson-annotations</artifactId>
150             <version>${jackson.version}</version>
151         </dependency>
152         <dependency>
153             <groupId>com.fasterxml.jackson.core</groupId>
154             <artifactId>jackson-databind</artifactId>
155             <version>${jackson.version}</version>
156         </dependency>
157         <dependency>
158             <groupId>com.fasterxml.jackson.core</groupId>
159             <artifactId>jackson-core</artifactId>
160             <version>${jackson.version}</version>
161         </dependency>
162         <dependency>
163             <groupId>com.fasterxml.jackson.dataformat</groupId>
164             <artifactId>jackson-dataformat-xml</artifactId>
165             <version>${jackson.version}</version>
166         </dependency>
167         <!-- 日志文件管理包 -->
168         <dependency>
169             <groupId>log4j</groupId>
170             <artifactId>log4j</artifactId>
171             <version>${log4j.version}</version>
172         </dependency>
173         <dependency>
174             <groupId>org.slf4j</groupId>
175             <artifactId>slf4j-api</artifactId>
176             <version>${slf4j.version}</version>
177         </dependency>
178         <dependency>
179             <groupId>org.slf4j</groupId>
180             <artifactId>slf4j-log4j12</artifactId>
181             <version>${slf4j.version}</version>
182         </dependency>
183     </dependencies>
184 
185     <dependencyManagement>
186         <dependencies>
187             <!--spring web-->
188             <dependency>
189                 <groupId>org.springframework</groupId>
190                 <artifactId>spring-web</artifactId>
191                 <version>${spring.version}</version>
192             </dependency>
193             <dependency>
194                 <groupId>org.springframework</groupId>
195                 <artifactId>spring-webmvc</artifactId>
196                 <version>${spring.version}</version>
197             </dependency>
198             <!--cglib-->
199             <dependency>
200                 <groupId>cglib</groupId>
201                 <artifactId>cglib</artifactId>
202                 <version>${cglib.version}</version>
203             </dependency>
204             <!-- mybatis -->
205             <dependency>
206                 <groupId>org.mybatis</groupId>
207                 <artifactId>mybatis</artifactId>
208                 <version>${mybatis.version}</version>
209             </dependency>
210             <dependency>
211                 <groupId>org.mybatis</groupId>
212                 <artifactId>mybatis-spring</artifactId>
213                 <version>${mybatisSpring.version}</version>
214             </dependency>
215             <!-- Mysql数据库驱动包 -->
216             <dependency>
217                 <groupId>mysql</groupId>
218                 <artifactId>mysql-connector-java</artifactId>
219                 <version>${mysql.version}</version>
220             </dependency>
221             <!-- connection pool -->
222             <dependency>
223                 <groupId>com.alibaba</groupId>
224                 <artifactId>druid</artifactId>
225                 <version>${druid.version}</version>
226                 <!--<scope>runtime</scope>-->
227             </dependency>
228             <!--servlet-->
229             <dependency>
230                 <groupId>javax.servlet</groupId>
231                 <artifactId>javax.servlet-api</artifactId>
232                 <version>${javaxServlet.version}</version>
233                 <scope>provided</scope>
234             </dependency>
235             <dependency>
236                 <groupId>javax.servlet.jsp</groupId>
237                 <artifactId>jsp-api</artifactId>
238                 <version>${jspApi.version}</version>
239                 <scope>provided</scope>
240             </dependency>
241             <dependency>
242                 <groupId>javax.servlet</groupId>
243                 <artifactId>jstl</artifactId>
244                 <version>${jstl.version}</version>
245             </dependency>
246             <!-- 映入JSON lib -->
247             <dependency>
248                 <groupId>net.sf.json-lib</groupId>
249                 <artifactId>json-lib</artifactId>
250                 <version>${jsonLib.version}</version>
251                 <classifier>jdk15</classifier>
252             </dependency>
253             <!-- jackson old -->
254             <dependency>
255                 <groupId>org.codehaus.jackson</groupId>
256                 <artifactId>jackson-core-asl</artifactId>
257                 <version>${jacksonOld.version}</version>
258             </dependency>
259             <dependency>
260                 <groupId>org.codehaus.jackson</groupId>
261                 <artifactId>jackson-mapper-asl</artifactId>
262                 <version>${jacksonOld.version}</version>
263             </dependency>
264             <!-- 用dom4j解析xml文件 -->
265             <dependency>
266                 <groupId>dom4j</groupId>
267                 <artifactId>dom4j</artifactId>
268                 <version>${dom4j.version}</version>
269             </dependency>
270             <!-- ehcache -->
271             <dependency>
272                 <groupId>net.sf.ehcache</groupId>
273                 <artifactId>ehcache-core</artifactId>
274                 <version>${ehcacheCore.version}</version>
275             </dependency>
276             <dependency>
277                 <groupId>net.sf.ehcache</groupId>
278                 <artifactId>ehcache-web</artifactId>
279                 <version>${ehcacheWeb.version}</version>
280             </dependency>
281             <!-- 上传组件包 -->
282             <dependency>
283                 <groupId>commons-fileupload</groupId>
284                 <artifactId>commons-fileupload</artifactId>
285                 <version>${commonsFileupload.version}</version>
286             </dependency>
287             <dependency>
288                 <groupId>commons-io</groupId>
289                 <artifactId>commons-io</artifactId>
290                 <version>${commonsIo.version}</version>
291             </dependency>
292             <dependency>
293                 <groupId>commons-codec</groupId>
294                 <artifactId>commons-codec</artifactId>
295                 <version>${commonsCodec.version}</version>
296             </dependency>
297             <dependency>
298                 <groupId>org.apache.commons</groupId>
299                 <artifactId>commons-collections4</artifactId>
300                 <version>${commonsCollections4.version}</version>
301             </dependency>
302             <dependency>
303                 <groupId>org.apache.commons</groupId>
304                 <artifactId>commons-lang3</artifactId>
305                 <version>3.3.2</version>
306             </dependency>
307             <!-- commons-beanutils -->
308             <dependency>
309                 <groupId>commons-beanutils</groupId>
310                 <artifactId>commons-beanutils</artifactId>
311                 <version>${commonsBeanutils.version}</version>
312                 <exclusions>
313                     <exclusion>
314                         <groupId>commons-logging</groupId>
315                         <artifactId>commons-logging</artifactId>
316                     </exclusion>
317                 </exclusions>
318             </dependency>
319             <!-- freemarker -->
320             <dependency>
321                 <groupId>org.freemarker</groupId>
322                 <artifactId>freemarker</artifactId>
323                 <version>${freemarker.version}</version>
324             </dependency>
325             <!-- poi -->
326             <dependency>
327                 <groupId>org.apache.poi</groupId>
328                 <artifactId>poi</artifactId>
329                 <version>${poi.version}</version>
330             </dependency>
331             <dependency>
332                 <groupId>org.apache.poi</groupId>
333                 <artifactId>poi-ooxml</artifactId>
334                 <version>${poi.version}</version>
335             </dependency>
336             <!-- org.apache.httpcomponents -->
337             <dependency>
338                 <groupId>org.apache.httpcomponents</groupId>
339                 <artifactId>httpcore</artifactId>
340                 <version>${httpcore.version}</version>
341             </dependency>
342             <dependency>
343                 <groupId>org.apache.httpcomponents</groupId>
344                 <artifactId>httpclient</artifactId>
345                 <version>${httpclient.version}</version>
346             </dependency>
347             <!-- com.sun.xml.ws/jaxws-rt -->
348             <dependency>
349                 <groupId>com.sun.xml.ws</groupId>
350                 <artifactId>jaxws-rt</artifactId>
351                 <version>${jaxwsRt.version}</version>
352             </dependency>
353             <!-- redis.clients/jedis -->
354             <dependency>
355                 <groupId>redis.clients</groupId>
356                 <artifactId>jedis</artifactId>
357                 <version>${jedis.version}</version>
358             </dependency>
359             <!-- com.rabbitmq/amqp-client -->
360             <dependency>
361                 <groupId>com.rabbitmq</groupId>
362                 <artifactId>amqp-client</artifactId>
363                 <version>${amqpClient.version}</version>
364             </dependency>
365             <!-- com.alibaba/fastjson -->
366             <dependency>
367                 <groupId>com.alibaba</groupId>
368                 <artifactId>fastjson</artifactId>
369                 <version>${fastjson.version}</version>
370             </dependency>
371             <!-- javax.annotation/jsr250-api -->
372             <dependency>
373                 <groupId>javax.annotation</groupId>
374                 <artifactId>jsr250-api</artifactId>
375                 <version>${jsr250.version}</version>
376             </dependency>
377         </dependencies>
378     </dependencyManagement>
379 
380     <!--&lt;!&ndash; tomcat8-maven-plugin *仓没有,所以配置 plugin 仓地址 &ndash;&gt;-->
381     <!--<pluginRepositories>-->
382         <!--<pluginRepository>-->
383             <!--<id>alfresco-public</id>-->
384             <!--<url>https://artifacts.alfresco.com/nexus/content/groups/public</url>-->
385         <!--</pluginRepository>-->
386         <!--<pluginRepository>-->
387             <!--<id>alfresco-public-snapshots</id>-->
388             <!--<url>https://artifacts.alfresco.com/nexus/content/groups/public-snapshots</url>-->
389             <!--<snapshots>-->
390                 <!--<enabled>true</enabled>-->
391                 <!--<updatePolicy>daily</updatePolicy>-->
392             <!--</snapshots>-->
393         <!--</pluginRepository>-->
394         <!--<pluginRepository>-->
395             <!--<id>beardedgeeks-releases</id>-->
396             <!--<url>http://beardedgeeks.googlecode.com/svn/repository/releases</url>-->
397         <!--</pluginRepository>-->
398     <!--</pluginRepositories>-->
399 
400     <build>
401         <plugins>
402             <!-- java编译插件 -->
403             <plugin>
404                 <groupId>org.apache.maven.plugins</groupId>
405                 <artifactId>maven-compiler-plugin</artifactId>
406                 <version>3.2</version>
407                 <configuration>
408                     <source>1.8</source>
409                     <target>1.8</target>
410                     <encoding>UTF-8</encoding>
411                 </configuration>
412             </plugin>
413         </plugins>
414 
415         <pluginManagement>
416             <plugins>
417                 <!-- 配置Tomcat插件 -->
418                 <plugin>
419                     <groupId>org.apache.tomcat.maven</groupId>
420                     <artifactId>tomcat8-maven-plugin</artifactId>
421                     <version>3.0-r1756463</version>
422                 </plugin>
423             </plugins>
424         </pluginManagement>
425     </build>
426 
427 </project>

  2.solution/webapi/pom.xml

  1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  3 
  4     <parent>
  5         <artifactId>solution</artifactId>
  6         <groupId>lm.solution</groupId>
  7         <version>1.0-SNAPSHOT</version>
  8     </parent>
  9 
 10     <modelVersion>4.0.0</modelVersion>
 11     <groupId>lm.solution</groupId>
 12     <artifactId>webapi</artifactId>
 13     <packaging>war</packaging>
 14     <version>1.0-SNAPSHOT</version>
 15     <name>webapi Maven Webapp</name>
 16     <url>http://maven.apache.org</url>
 17 
 18     <dependencies>
 19         <!--Module-->
 20         <dependency>
 21             <groupId>lm.solution</groupId>
 22             <artifactId>service</artifactId>
 23             <version>1.0-SNAPSHOT</version>
 24         </dependency>
 25         <dependency>
 26             <groupId>lm.solution</groupId>
 27             <artifactId>common</artifactId>
 28             <version>1.0-SNAPSHOT</version>
 29         </dependency>
 30 
 31         <!--Libary-->
 32         <dependency>
 33             <groupId>cglib</groupId>
 34             <artifactId>cglib</artifactId>
 35         </dependency>
 36 
 37         <!--mybatis spring 插件 -->
 38         <dependency>
 39             <groupId>org.mybatis</groupId>
 40             <artifactId>mybatis-spring</artifactId>
 41         </dependency>
 42         <dependency>
 43             <groupId>javax.servlet</groupId>
 44             <artifactId>javax.servlet-api</artifactId>
 45             <scope>provided</scope>
 46         </dependency>
 47         <dependency>
 48             <groupId>javax.servlet.jsp</groupId>
 49             <artifactId>jsp-api</artifactId>
 50             <scope>provided</scope>
 51         </dependency>
 52         <dependency>
 53             <groupId>javax.servlet</groupId>
 54             <artifactId>jstl</artifactId>
 55         </dependency>
 56         <!-- 映入JSON lib -->
 57         <dependency>
 58             <groupId>net.sf.json-lib</groupId>
 59             <artifactId>json-lib</artifactId>
 60             <classifier>jdk15</classifier>
 61         </dependency>
 62         <!-- 用dom4j解析xml文件 -->
 63         <dependency>
 64             <groupId>dom4j</groupId>
 65             <artifactId>dom4j</artifactId>
 66         </dependency>
 67         <!-- ehcache -->
 68         <dependency>
 69             <groupId>net.sf.ehcache</groupId>
 70             <artifactId>ehcache-core</artifactId>
 71         </dependency>
 72         <dependency>
 73             <groupId>net.sf.ehcache</groupId>
 74             <artifactId>ehcache-web</artifactId>
 75         </dependency>
 76         <!-- 上传组件包 -->
 77         <dependency>
 78             <groupId>commons-fileupload</groupId>
 79             <artifactId>commons-fileupload</artifactId>
 80         </dependency>
 81         <dependency>
 82             <groupId>commons-io</groupId>
 83             <artifactId>commons-io</artifactId>
 84         </dependency>
 85         <dependency>
 86             <groupId>commons-codec</groupId>
 87             <artifactId>commons-codec</artifactId>
 88         </dependency>
 89         <dependency>
 90             <groupId>org.apache.commons</groupId>
 91             <artifactId>commons-collections4</artifactId>
 92         </dependency>
 93         <dependency>
 94             <groupId>org.apache.commons</groupId>
 95             <artifactId>commons-lang3</artifactId>
 96         </dependency>
 97         <!-- commons-beanutils -->
 98         <dependency>
 99             <groupId>commons-beanutils</groupId>
100             <artifactId>commons-beanutils</artifactId>
101             <exclusions>
102                 <exclusion>
103                     <groupId>commons-logging</groupId>
104                     <artifactId>commons-logging</artifactId>
105                 </exclusion>
106             </exclusions>
107         </dependency>
108         <!-- freemarker -->
109         <dependency>
110             <groupId>org.freemarker</groupId>
111             <artifactId>freemarker</artifactId>
112         </dependency>
113 
114     </dependencies>
115 
116     <build>
117         <finalName>webapi</finalName>
118 
119         <plugins>
120             <plugin>
121                 <groupId>org.apache.tomcat.maven</groupId>
122                 <artifactId>tomcat8-maven-plugin</artifactId>
123             </plugin>
124         </plugins>
125     </build>
126 </project>

  3.solution/mapper/pom.xml

 1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 2          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 3     <parent>
 4         <artifactId>solution</artifactId>
 5         <groupId>lm.solution</groupId>
 6         <version>1.0-SNAPSHOT</version>
 7     </parent>
 8     <modelVersion>4.0.0</modelVersion>
 9 
10     <groupId>lm.solution</groupId>
11     <artifactId>mapper</artifactId>
12     <version>1.0-SNAPSHOT</version>
13     <packaging>jar</packaging>
14 
15     <name>mapper</name>
16     <url>http://maven.apache.org</url>
17 
18     <properties>
19         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
20     </properties>
21 
22     <dependencies>
23         <!--Module-->
24         <dependency>
25             <groupId>lm.solution</groupId>
26             <artifactId>pojo</artifactId>
27             <version>1.0-SNAPSHOT</version>
28         </dependency>
29 
30         <!--Libary-->
31         <dependency><!-- mybatis核心包 -->
32             <groupId>org.mybatis</groupId>
33             <artifactId>mybatis</artifactId>
34         </dependency>
35         <dependency><!-- Mysql数据库驱动包 -->
36             <groupId>mysql</groupId>
37             <artifactId>mysql-connector-java</artifactId>
38         </dependency>
39         <dependency><!-- connection pool -->
40             <groupId>com.alibaba</groupId>
41             <artifactId>druid</artifactId>
42             <scope>runtime</scope>
43         </dependency>
44     </dependencies>
45 </project>

  4.web.xml

 1 <!DOCTYPE web-app PUBLIC
 2         "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 3         "http://java.sun.com/dtd/web-app_2_3.dtd" >
 4 
 5 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 6          xmlns="http://java.sun.com/xml/ns/javaee"
 7          xsi:schemaLocation="
 8             http://java.sun.com/xml/ns/javaee
 9             http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
10          id="WebApp_ID"
11          version="3.0">
12 
13   <context-param>
14     <description>配置Spring配置文件路径</description>
15     <param-name>contextConfigLocation</param-name>
16     <param-value>classpath:spring-context.xml</param-value><!-- 如果是监听多个文件,可用‘,’隔开 -->
17   </context-param>
18   <context-param><!--log4j配置文件加载-->
19     <param-name>log4jConfigLocation</param-name>
20     <param-value>classpath:log4j.properties</param-value>
21   </context-param>
22   <context-param><!--启动一个watchdog线程每1800秒扫描一下log4j配置文件的变化-->
23     <param-name>log4jRefreshInterval</param-name>
24     <param-value>1800000</param-value>
25   </context-param>
26 
27   <listener>
28     <description>配置Spring上下文监听器</description>
29     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
30   </listener>
31   <listener>
32     <description>Introspector缓存清除监听器</description>
33     <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
34   </listener>
35   <listener>
36     <description>request监听器</description>
37     <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
38   </listener>
39   <listener><!--spring log4j监听器-->
40     <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
41   </listener>
42 
43   <filter><!-- 配置Spring字符编码过滤器 -->
44     <filter-name>encodingFilter</filter-name>
45     <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
46     <init-param>
47       <param-name>encoding</param-name>
48       <param-value>UTF-8</param-value>
49     </init-param>
50     <init-param>
51       <param-name>forceEncoding</param-name>
52       <param-value>true</param-value>
53     </init-param>
54   </filter>
55   <filter-mapping>
56     <filter-name>encodingFilter</filter-name>
57     <url-pattern>/*</url-pattern>
58   </filter-mapping>
59 
60   <servlet><!-- Spring MVC 核心控制器 DispatcherServlet 配置 -->
61     <servlet-name>SpringMVC</servlet-name>
62     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
63     <init-param><!--以下init-param是自定义SpringMVC的配置文件的位置 -->
64       <param-name>contextConfigLocation</param-name>
65       <param-value>classpath:spring-mvc.xml</param-value>
66     </init-param>
67     <load-on-startup>1</load-on-startup>
68   </servlet>
69   <servlet-mapping><!-- 拦截设置 -->
70     <servlet-name>SpringMVC</servlet-name>
71     <url-pattern>/</url-pattern>
72   </servlet-mapping>
73 
74   <session-config><!-- session 时间 -->
75     <session-timeout>30</session-timeout>
76   </session-config>
77   
78   <welcome-file-list>
79     <welcome-file>/WEB-INF/index.html</welcome-file>
80   </welcome-file-list>
81 
82 </web-app>

  5.spring-mvc.xml

 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:p="http://www.springframework.org/schema/p"
 5        xmlns:context="http://www.springframework.org/schema/context"
 6        xmlns:mvc="http://www.springframework.org/schema/mvc"
 7        xsi:schemaLocation="
 8         http://www.springframework.org/schema/beans
 9         http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
10         http://www.springframework.org/schema/context
11         http://www.springframework.org/schema/context/spring-context-4.0.xsd
12         http://www.springframework.org/schema/mvc
13         http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
14 
15     <!--
16         启用spring mvc 注解, 默认的注解映射的支持
17         自动注册 RequestMappingHandlerMapping RequestMappingHandlerAdapter 两个 bean
18         这是 Spring mvc 分发请求所必须的
19         并提供了数据绑定支持
20         读写XML支持
21         读写Json支持
22     -->
23     <mvc:annotation-driven/>
24     <!--
25         对静态资源文件的访问,
26         将无法mapping到Controller的path
27         交给default servlet handler处理
28     -->
29     <mvc:default-servlet-handler />
30 
31     <context:annotation-config/><!-- 开启注解处理器 -->
32     <context:component-scan base-package="lm.solution"/>
    <!-- 自动扫描包,注册 @Controller @Service @Repository @Component 等注解的类成为 bean --> 33 34 <bean id="mappingJacksonHttpMessageConverter" 35 class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
        <!-- 支持返回json(避免IE在ajax请求时,返回json出现下载文件 ) --> 36 <property name="supportedMediaTypes"> 37 <list> 38 <value>text/html;charset=UTF-8</value> 39 <value>text/json;charset=UTF-8</value> 40 <value>application/json;charset=UTF-8</value> 41 </list> 42 </property> 43 </bean> 44 45 46 47 </beans>

  6.spring-context.xml

  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:tx="http://www.springframework.org/schema/tx"
  6        xmlns:aop="http://www.springframework.org/schema/aop"
  7        xsi:schemaLocation="
  8             http://www.springframework.org/schema/beans
  9             http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
 10             http://www.springframework.org/schema/context
 11             http://www.springframework.org/schema/context/spring-context-4.0.xsd
 12             http://www.springframework.org/schema/tx
 13             http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
 14             http://www.springframework.org/schema/aop
 15             http://www.springframework.org/schema/aop/spring-aop-4.0.xsd"
 16        default-lazy-init="true">
 17 
 18     <context:property-placeholder location="classpath:dbconfig.properties" />
 19 
 20     <!-- dataSource 配置数据源 -->
 21     <bean id="dataSource"
 22           class="com.alibaba.druid.pool.DruidDataSource"
 23           init-method="init"
 24           destroy-method="close">
 25         <!-- 基本属性 url、user、password -->
 26         <property name="url" value="${jdbc.url}" />
 27         <property name="username" value="${jdbc.username}" />
 28         <property name="password" value="${jdbc.password}" />
 29         <!-- 配置初始化大小、最小、最大 -->
 30         <property name="initialSize" value="1" />
 31         <property name="minIdle" value="1" />
 32         <property name="maxActive" value="20" />
 33         <!-- 配置获取连接等待超时的时间 -->
 34         <property name="maxWait" value="60000" />
 35         <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
 36         <property name="timeBetweenEvictionRunsMillis" value="60000" />
 37         <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
 38         <property name="minEvictableIdleTimeMillis" value="300000" />
 39         <property name="validationQuery" value="SELECT 'x'" />
 40         <property name="testWhileIdle" value="true" />
 41         <property name="testOnBorrow" value="false" />
 42         <property name="testOnReturn" value="false" />
 43         <!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
 44         <property name="poolPreparedStatements" value="false" />
 45         <property name="maxPoolPreparedStatementPerConnectionSize" value="20" />
 46         <!-- 配置监控统计拦截的filters -->
 47         <property name="filters" value="stat" />
 48     </bean>
 49 
 50     <!-- mybatis和spring完美整合,不需要mybatis的配置映射文件 -->
 51     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
 52         <property name="dataSource" ref="dataSource"/>
 53     </bean>
 54 
 55     <!-- DAO接口所在包名,Spring会自动查找其下的类 -->
 56     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
 57         <property name="basePackage" value="lm.solution"/>
 58         <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
 59     </bean>
 60 
 61     <!-- 对dataSource 数据源进行事务管理 -->
 62     <bean id="transactionManager"
 63           class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
 64         <property name="dataSource" ref="dataSource"></property>
 65     </bean>
 66 
 67     <!-- 事务管理 通知 -->
 68     <tx:advice id="txAdvice" transaction-manager="transactionManager">
 69         <tx:attributes>
 70             <!-- 对insert,create,update,modify,delete,remove 开头的方法进行事务管理,只要有异常就回滚 -->
 71             <tx:method name="insert*" propagation="REQUIRED" rollback-for="java.lang.Throwable"  read-only="false"/>
 72             <tx:method name="add*" propagation="REQUIRED" rollback-for="java.lang.Throwable"  read-only="false"/>
 73             <tx:method name="create*" propagation="REQUIRED" rollback-for="java.lang.Throwable"  read-only="false"/>
 74             <tx:method name="update*" propagation="REQUIRED" rollback-for="java.lang.Throwable"  read-only="false"/>
 75             <tx:method name="modify*" propagation="REQUIRED" rollback-for="java.lang.Throwable"  read-only="false"/>
 76             <tx:method name="delete*" propagation="REQUIRED" rollback-for="java.lang.Throwable"  read-only="false"/>
 77             <tx:method name="remove*" propagation="REQUIRED" rollback-for="java.lang.Throwable" read-only="false"/>
 78             <!-- find,get,select,count开头的方法,开启只读,提高数据库访问性能 -->
 79             <tx:method name="find*" read-only="true" />
 80             <tx:method name="get*" read-only="true" />
 81             <tx:method name="select*" read-only="true" />
 82             <tx:method name="count*" read-only="true" />
 83             <!-- 对其他方法 使用默认的事务管理 -->
 84             <tx:method name="*" />
 85         </tx:attributes>
 86     </tx:advice>
 87 
 88     <!-- 配置 Annotation 驱动,扫描@Transactional注解的类定义事务  -->
 89     <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>
 90 
 91     <!-- 事务 aop 配置 -->
 92     <aop:config>
 93         <aop:pointcut id="serviceMethods" expression="execution(public * lm.solution.service.mysql.impl..*(..))" />
 94         <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethods" />
 95     </aop:config>
 96 
 97     <!-- 开启基于@AspectJ切面的注解处理器 -->
 98     <aop:aspectj-autoproxy proxy-target-class="true" />
 99 
100 </beans>

  7.dbconfig.properties

1 #MySQL
2 jdbc.driver=com.mysql.jdbc.Driver
3 jdbc.url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true
4 jdbc.username=root
5 jdbc.password=liumeng

  8.log4j.properties

 1 #日志输出级别
 2 log4j.rootLogger=debug,stdout,D,E
 3 
 4 #设置stdout的日志输出控制台
 5 log4j.appender.stdout=org.apache.log4j.ConsoleAppender
 6 #输出日志到控制台的方式,默认为System.out
 7 log4j.appender.stdout.Target = System.out
 8 #设置使用灵活布局
 9 log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
10 #灵活定义输出格式
11 log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} -[%p]  method:[%c (%rms)] - %m%n
12 
13 #每天产生一个日志文件
14 log4j.appender.D=org.apache.log4j.DailyRollingFileAppender
15 #设置的输出日志
16 log4j.appender.D.File=F:/ideaSpace/springmvc/logs/log.txt
17 #设置的日志最大限制
18 log4j.appender.D.MaxFileSize=6000KB
19 #最多只保存20个备份文件
20 log4j.appender.D.MaxBackupIndex=20
21 #输出INFO级别以上的日志
22 og4j.appender.D.Threshold=debug
23 log4j.appender.D.Append = true
24 log4j.appender.D.ImmediateFlush = true
25 #log4j.appender.D.DatePattern ='.'yyyy-MM-dd
26 #设置使用灵活布局
27 log4j.appender.D.layout=org.apache.log4j.PatternLayout
28 #灵活定义输出格式
29 log4j.appender.D.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} -[%p]  method:[%l (%rms)] - %m%n
30 
31 log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
32 log4j.appender.E.File =F:/ideaSpace/springmvc/logs/error/error.txt
33 log4j.appender.E.Append = true
34 log4j.appender.E.Threshold = ERROR
35 #log4j.appender.E.DatePattern = '_'yyyyMMdd'.log'
36 log4j.appender.E.layout = org.apache.log4j.PatternLayout
37 log4j.appender.E.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm:ss,SSS} -[%p]  method:[%l (%rms)] - %m%n

  9.RESTfulController.java

  1 package lm.solution.webapi;
  2 
  3 import lm.solution.pojo.entity.User;
  4 import lm.solution.service.mysql.UserService;
  5 import org.springframework.beans.factory.annotation.Autowired;
  6 import org.springframework.beans.factory.annotation.Qualifier;
  7 import org.springframework.http.HttpHeaders;
  8 import org.springframework.http.HttpStatus;
  9 import org.springframework.http.MediaType;
 10 import org.springframework.http.ResponseEntity;
 11 import org.springframework.web.bind.annotation.RestController;
 12 import org.springframework.web.bind.annotation.RequestMapping;
 13 import org.springframework.web.bind.annotation.RequestMethod;
 14 import org.springframework.web.bind.annotation.PathVariable;
 15 import org.springframework.web.bind.annotation.RequestBody;
 16 import org.springframework.web.util.UriComponentsBuilder;
 17 
 18 import java.util.List;
 19 /**
 20  * @RestController 是一个组合注解,相当于 @Controller 与 @ResponseBody 的结合体
 21  * */
 22 @RestController
 23 @RequestMapping(value = "/api")
 24 public class RESTfulController {
 25 
 26     @Autowired
 27     @Qualifier("userService")
 28     private UserService userService;
 29 
 30     //-------------------Retrieve All Users--------------------------------------------------------
 31     @RequestMapping(
 32             value = "/user",
 33             method = RequestMethod.GET,
 34             produces={"application/json;;charset=UTF-8"})
 35     public ResponseEntity<List<User>> listAllUsers() {
 36 
 37         List<User> users = userService.findAllUsers();
 38         if (users.isEmpty()) {
 39             return new ResponseEntity<List<User>>(HttpStatus.NO_CONTENT);
 40         }
 41         return new ResponseEntity<List<User>>(users, HttpStatus.OK);
 42 
 43     }
 44 
 45     //-------------------Retrieve Single User--------------------------------------------------------
 46     @RequestMapping(
 47             value = "/user/{id}",
 48             method = RequestMethod.GET,
 49             produces = MediaType.APPLICATION_JSON_VALUE)
 50     public ResponseEntity<User> getUser(@PathVariable("id") long id) {
 51 
 52         System.out.println("Fetching User with id " + id);
 53 
 54         User user = userService.findById(id);
 55 
 56         if (user == null) {
 57             System.out.println("User with id " + id + " not found");
 58             return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
 59         }
 60 
 61         return new ResponseEntity<User>(user, HttpStatus.OK);
 62 
 63     }
 64 
 65     //-------------------Create a User--------------------------------------------------------
 66     @RequestMapping(
 67             value = "/user",
 68             method = RequestMethod.POST)
 69     public ResponseEntity<Void> createUser(
 70             @RequestBody User user,
 71             UriComponentsBuilder ucBuilder) {
 72 
 73         System.out.println("Creating User " + user.getName());
 74 
 75         if(userService.isUserExist(user)){
 76             System.out.println("A User with name " + user.getName() + " already exist");
 77             return  new ResponseEntity<Void>(HttpStatus.CONFLICT);
 78         }
 79 
 80         userService.saveUser(user);
 81 
 82         HttpHeaders headers=new HttpHeaders();
 83         headers.setLocation(ucBuilder.path("/api/user/{id}").buildAndExpand(user.getId()).toUri());
 84         return  new ResponseEntity<Void>(headers,HttpStatus.CREATED);
 85 
 86     }
 87 
 88     //------------------- Update a User --------------------------------------------------------
 89     @RequestMapping(value = "/user/{id}",method = RequestMethod.PUT)
 90     public ResponseEntity<User> updateUser(
 91             @PathVariable("id") long id,
 92             @RequestBody User user){
 93 
 94         System.out.println("Updating User " + id);
 95 
 96         User currentUser=userService.findById(id);
 97 
 98         if(currentUser==null){
 99             System.out.println("User with id " + id + " not found");
100             return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
101         }
102 
103         currentUser.setName(user.getName());
104         currentUser.setAge(user.getAge());
105         currentUser.setSalary(user.getSalary());
106 
107         userService.updateUser(user);
108         return new ResponseEntity<User>(currentUser, HttpStatus.OK);
109 
110     }
111 
112     //------------------- Delete a User --------------------------------------------------------
113     @RequestMapping(value = "/user/{id}",method = RequestMethod.DELETE)
114     public ResponseEntity<User> deleteUser(@PathVariable("id") long id){
115 
116         System.out.println("Fetching & Deleting User with id " + id);
117 
118         User user=userService.findById(id);
119         if(user==null){
120             System.out.println("Unable to delete. User with id " + id + " not found");
121             return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
122         }
123 
124         userService.deleteUser(id);
125         return new ResponseEntity<User>(HttpStatus.NO_CONTENT);
126 
127     }
128 
129     //------------------- Delete All Users --------------------------------------------------------
130     @RequestMapping(value="/user",method = RequestMethod.DELETE)
131     public ResponseEntity<User> deleteAllUsers() {
132 
133         System.out.println("Deleting All Users");
134 
135         userService.deleteAllUsers();
136         return new ResponseEntity<User>(HttpStatus.NO_CONTENT);
137 
138     }
139 
140 }

 

 

 

 

                                         蒙

                                    2018-05-13 18:55 周日