SSM(Spring+SpringMVC+Mybatis)框架搭建詳細教程【附源代碼Demo】

【前言】

  應某網絡友人邀約,須要一個SSM框架的Demo做爲基礎學習資料,因而乎,就有了本文。一個從零開始的SSM框架Demo對一個新手來講,是很是重要的,可大大減小在學習過程當中遇到的各類各樣的坑,說到最後,也算是助人爲樂吧!下面咱們從零開始進行SSM框架的搭建,在介紹最後,我會把項目部署在GitHub以便須要Demo的親朋好友們進行下載~~~css

  https://github.com/sevenTiny/Demo.SSM (訪問記得Star哦~)html

  本Demo是在IDEA下搭建的Maven項目,在進行下面閱讀前先了解這一點!java

【開發環境】

  1.操做系統:Windows7 ×64 Sp1

  

  2.Java-Version:1.8.0_101

  

  3.IDE:IntelliJ IDEA 2017.2.2 x64

  

1、新建項目

  運行IDEA,進入初始化界面,而後咱們選擇新建項目(進入主界面新建項目也是同樣的)

  

  在Maven選項卡里面找到對應的java web選項,而後咱們點下一步

  

  這一步填入組織等信息,這裏比較隨意,按照本身的需求進行填寫,而後下一步

  

  這裏我早已配置好本地Maven倉庫,所以直接默認便可。若是沒進行配置本地默認倉庫的話,請網上查找對應的資料進行配置

  

  輸入Project name,和須要保存的路徑,而後finish

  

  去泡一杯咖啡吧,這裏須要一小段時間哦~mysql

  稍等片刻,idea已經爲咱們自動建好了一切。到這裏,咱們的第一步,新建項目階段已經完成,歡慶一下,進入下一個階段。

   

  新建好項目後,咱們首先打開SSM_Demo,修改一下JDK版本。git

  

  

  在settings裏面對項目版本進行修改:github

  

  原來是1_5,如今改成1_8,可能會存在spring等框架版本和jdk版本不兼容問題,所以,提早升級了版本。web

2、目錄結構調整

首先咱們配置Maven的項目結構,選擇Project Structure

  

  選擇Modules標籤頁,而後新建並標識對應的項目結構

  最終的文件結構以下所示:

  

  

 

  - Java爲主Java代碼文件夾spring

    - Controllers 控制器文件文件夾sql

    - Dao (數據訪問)層文件夾數據庫

    - Service(業務邏輯)層文件夾

    - Entity(實體)層文件夾

  - resources資源文件夾

    - mapper mybatis sql文件夾

  - webapp web頁面文件夾

  - Test 測試文件夾

3、Maven包的初始化

Maven是採用配置文件的方式進行jar包的自動導入,所以,咱們須要進行對配置文件的修改來進行jar包的導入。

  打開pom.xml文件

  

   添加咱們將會用到的一系列jar包配置(這裏將個人配置直接複製過來,做爲參考)

  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   <modelVersion>4.0.0</modelVersion>
  4   <groupId>QX_JFrame</groupId>
  5   <artifactId>Demo</artifactId>
  6   <packaging>war</packaging>
  7   <version>1.0-SNAPSHOT</version>
  8   <name>Demo Maven Webapp</name>
  9   <url>http://maven.apache.org</url>
 10   <dependencies>
 11     <!--Unit Test - 單元測試-->
 12     <dependency>
 13       <groupId>junit</groupId>
 14       <artifactId>junit</artifactId>
 15       <version>4.12</version>
 17     </dependency>
 18     <!--Spring-->
 19     <dependency>
 20       <groupId>org.springframework</groupId>
 21       <artifactId>spring-core</artifactId>
 22       <version>4.3.5.RELEASE</version>
 23     </dependency>
 24     <dependency>
 25       <groupId>org.springframework</groupId>
 26       <artifactId>spring-aop</artifactId>
 27       <version>4.3.5.RELEASE</version>
 28     </dependency>
 29     <dependency>
 30       <groupId>org.springframework</groupId>
 31       <artifactId>spring-orm</artifactId>
 32       <version>4.3.5.RELEASE</version>
 33     </dependency>
 34     <!--Spring transaction-->
 35     <dependency>
 36       <groupId>org.springframework</groupId>
 37       <artifactId>spring-tx</artifactId>
 38       <version>4.3.5.RELEASE</version>
 39     </dependency>
 40     <dependency>
 41       <groupId>org.springframework</groupId>
 42       <artifactId>spring-test</artifactId>
 43       <version>4.3.5.RELEASE</version>
 44     </dependency>
 45     <dependency>
 46       <groupId>org.springframework</groupId>
 47       <artifactId>spring-mock</artifactId>
 48       <version>2.0.8</version>
 49     </dependency>
 50     <dependency>
 51       <groupId>org.springframework</groupId>
 52       <artifactId>spring-jdbc</artifactId>
 53       <version>4.3.5.RELEASE</version>
 54     </dependency>
 55     <dependency>
 56       <groupId>org.springframework</groupId>
 57       <artifactId>spring-context</artifactId>
 58       <version>4.3.5.RELEASE</version>
 59     </dependency>
 60     <dependency>
 61       <groupId>org.springframework</groupId>
 62       <artifactId>spring-context-support</artifactId>
 63       <version>4.3.5.RELEASE</version>
 64     </dependency>
 65     <dependency>
 66       <groupId>org.springframework</groupId>
 67       <artifactId>spring-expression</artifactId>
 68       <version>4.3.5.RELEASE</version>
 69     </dependency>
 70     <!--Spring Web + Spring MVC-->
 71     <dependency>
 72       <groupId>org.springframework</groupId>
 73       <artifactId>spring-web</artifactId>
 74       <version>4.3.1.RELEASE</version>
 75     </dependency>
 76     <dependency>
 77       <groupId>org.springframework</groupId>
 78       <artifactId>spring-webmvc</artifactId>
 79       <version>4.3.1.RELEASE</version>
 80     </dependency>
 81 
 82     <dependency>
 83       <groupId>com.github.pagehelper</groupId>
 84       <artifactId>pagehelper</artifactId>
 85       <version>3.7.3</version>
 86     </dependency>
 87     <dependency>
 88       <groupId>com.github.jsqlparser</groupId>
 89       <artifactId>jsqlparser</artifactId>
 90       <version>0.9.1</version>
 91     </dependency>
 92     <!--mysql jdbc-->
 93     <dependency>
 94       <groupId>mysql</groupId>
 95       <artifactId>mysql-connector-java</artifactId>
 96       <version>5.1.38</version>
 97     </dependency>
 98     <!--c3p0-->
 99     <dependency>
100       <groupId>c3p0</groupId>
101       <artifactId>c3p0</artifactId>
102       <version>0.9.1.2</version>
103     </dependency>
104     <!--NoClassDefFoundError: javax/servlet/jsp/jstl/core/Config-->
105     <!-- https://mvnrepository.com/artifact/jstl/jstl -->
106     <dependency>
107       <groupId>jstl</groupId>
108       <artifactId>jstl</artifactId>
109       <version>1.2</version>
110     </dependency>
111     <!--file upload jar package-->
112     <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
113     <dependency>
114       <groupId>commons-fileupload</groupId>
115       <artifactId>commons-fileupload</artifactId>
116       <version>1.3.1</version>
117     </dependency>
118     <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
119     <dependency>
120       <groupId>commons-io</groupId>
121       <artifactId>commons-io</artifactId>
122       <version>2.4</version>
123     </dependency>
124     <!--json-->
125     <!-- https://mvnrepository.com/artifact/org.json/json -->
126     <dependency>
127       <groupId>org.json</groupId>
128       <artifactId>json</artifactId>
129       <version>20160212</version>
130     </dependency>
131     <!-- https://mvnrepository.com/artifact/net.sf.json-lib/json-lib -->
132     <dependency>
133       <groupId>net.sf.json-lib</groupId>
134       <artifactId>json-lib</artifactId>
135       <version>2.4</version>
136     </dependency>
137     <!-- https://mvnrepository.com/artifact/commons-lang/commons-lang -->
138     <dependency>
139       <groupId>commons-lang</groupId>
140       <artifactId>commons-lang</artifactId>
141       <version>2.6</version>
142     </dependency>
143     <!-- https://mvnrepository.com/artifact/commons-beanutils/commons-beanutils -->
144     <dependency>
145       <groupId>commons-beanutils</groupId>
146       <artifactId>commons-beanutils</artifactId>
147       <version>1.8.3</version>
148     </dependency>
149     <!-- https://mvnrepository.com/artifact/commons-collections/commons-collections -->
150     <dependency>
151       <groupId>commons-collections</groupId>
152       <artifactId>commons-collections</artifactId>
153       <version>3.2.1</version>
154     </dependency>
155     <!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
156     <dependency>
157       <groupId>commons-logging</groupId>
158       <artifactId>commons-logging</artifactId>
159       <version>1.2</version>
160     </dependency>
161     <!-- https://mvnrepository.com/artifact/net.sf.ezmorph/ezmorph -->
162     <dependency>
163       <groupId>net.sf.ezmorph</groupId>
164       <artifactId>ezmorph</artifactId>
165       <version>1.0.6</version>
166     </dependency>
167     <!--json serialize and deserialization-->
168     <!-- 引入fastjson依賴 -->
169     <dependency>
170       <groupId>com.alibaba</groupId>
171       <artifactId>fastjson</artifactId>
172       <version>1.2.12</version>
173     </dependency>
174     <!-- 引入gson依賴 -->
175     <dependency>
176       <groupId>com.google.code.gson</groupId>
177       <artifactId>gson</artifactId>
178       <version>2.6.2</version>
179     </dependency>
180     <!--Base64 加解密-->
181     <!-- https://mvnrepository.com/artifact/net.iharder/base64 -->
182     <dependency>
183       <groupId>net.iharder</groupId>
184       <artifactId>base64</artifactId>
185       <version>2.3.8</version>
186     </dependency>
187     <!-- https://mvnrepository.com/artifact/commons-codec/commons-codec -->
188     <dependency>
189       <groupId>commons-codec</groupId>
190       <artifactId>commons-codec</artifactId>
191       <version>1.10</version>
192     </dependency>
193     <!--log4j-->
194     <!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core -->
195     <dependency>
196       <groupId>org.apache.logging.log4j</groupId>
197       <artifactId>log4j-core</artifactId>
198       <version>2.6.2</version>
199     </dependency>
200     <dependency>
201       <groupId>org.jetbrains</groupId>
202       <artifactId>annotations-java5</artifactId>
203       <version>RELEASE</version>
204     </dependency>
205     <!--mybatis-->
206     <dependency>
207       <groupId>org.mybatis</groupId>
208       <artifactId>mybatis</artifactId>
209       <version>3.3.0</version>
210     </dependency>
211     <dependency>
212       <groupId>org.mybatis</groupId>
213       <artifactId>mybatis-spring</artifactId>
214       <version>1.2.3</version>
215     </dependency>
216   </dependencies>
217   <build>
218     <finalName>Demo</finalName>
219   </build>
220 </project>

  待配置好的jar包都自動下載並導入後,咱們maven包的導入階段就完成了,下面咱們開始整合各個組件。

4、Spring MVC的配置

   在resources資源文件夾下新建spring-servlet.xml文件,並在配置文件中聲明spring mvc框架對控制器、頁面、資源的訪問

  

  在其中添加下面配置標籤信息:

 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:mvc="http://www.springframework.org/schema/mvc"
 6        xsi:schemaLocation="http://www.springframework.org/schema/beans
 7 http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
 8 http://www.springframework.org/schema/context
 9 http://www.springframework.org/schema/context/spring-context-3.1.xsd
10 http://www.springframework.org/schema/mvc
11 http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">
12 
13     <!-- 啓動註解驅動的Spring MVC功能,註冊請求url和註解POJO類方法的映射-->
14     <mvc:annotation-driven >
15 
16     </mvc:annotation-driven>
17 
18     <!-- 啓動包掃描功能,以便註冊帶有@Controllers、@service、@repository、@Component等註解的類成爲spring的bean -->
19     <context:component-scan base-package="Controllers" />
20     <!-- 對模型視圖名稱的解析,在請求時模型視圖名稱添加先後綴 -->
21     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
22         <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
23         <property name="prefix" value="/"/>    <!-- 前綴 -->
24         <property name="suffix" value=".jsp"/>    <!-- 後綴 -->
25     </bean>
26     <!-- 訪問靜態文件(jpg,js,css)的方法 -->
27     <!--<mvc:resources location="/files/" mapping="/files/**" />-->
28     <!--<mvc:resources location="/scripts/" mapping="/scripts/**" />-->
29     <!--<mvc:resources location="/styles/" mapping="/styles/**" />-->
30     <!--<mvc:resources location="/Views/" mapping="/Views/**" />-->
31 </beans>

  

  這裏的Controllers對應的是咱們以前新建好的Controllers包文件夾。

  對web.xml進行配置,將咱們剛纔添加的spring-servlet.xml配置進去

  

  

  這裏的classpath爲resources資源目錄

  這一步配置的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 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 5          xmlns="http://java.sun.com/xml/ns/javaee"
 6          xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
 7          version="3.0">
 8   <display-name>Archetype Created Web Application</display-name>
 9   <welcome-file-list>
10     <welcome-file>/index.jsp</welcome-file>
11   </welcome-file-list>
12   <!-- Spring MVC配置 -->
13   <servlet>
14     <servlet-name>spring</servlet-name>
15     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
16     <!--Spring-servlet.xml config-->
17     <init-param>
18       <param-name>contextConfigLocation</param-name>
19       <param-value>classpath:spring-servlet.xml</param-value>
20     </init-param>
21     <!-- load-on-startup元素標記容器是否在啓動的時候就加載這個servlet(實例化並調用其init()方法) -->
22     <load-on-startup>1</load-on-startup>
23   </servlet>
24   <servlet-mapping>
25     <servlet-name>spring</servlet-name>
26     <url-pattern>/</url-pattern>
27   </servlet-mapping>
28 </web-app>

  咱們新建一個控制器測試一下(在Controllers包新建java類,RequestTestController):

  

  接下來在RequestTestController裏面寫一個rest api接口:

  

  接口代碼以下:

 1 package Controllers;
 2 
 3 import org.springframework.web.bind.annotation.GetMapping;
 4 import org.springframework.web.bind.annotation.RequestMapping;
 5 import org.springframework.web.bind.annotation.RestController;
 6 
 7 @RestController
 8 @RequestMapping("/api/RequestTest")
 9 public class RequestTestController {
10 
11     @GetMapping()
12     public String TestString(){
13         return "this is a test string. Time:2017-10-29 20:42:00";
14     }
15 }

  這樣,咱們即可以經過url地址來進行訪問咱們的接口數據

  

  在右上角的運行服務器配置按鈕,打開服務器配置項

   

  這裏若是左側列表是空的話,咱們就須要點擊加號進行服務器的添加,選擇Tomcat Server下的Local。而後點擊剛剛添加的標籤,在右側輸入Server Name,下面會自動提示設置編譯方式,選一個編譯方式,而後點擊OK便可(這一步的前提是裝好了Tomcat服務器,若是沒有安裝,則須要先安裝Tomcat服務器)。

  而後咱們點擊右上角的運行,若是沒有什麼問題的話,咱們的控制檯界面會提示服務啓動成功!(我這樣下來是不會出問題的)

  

  等瀏覽器打開之後,咱們輸入咱們配置的api地址:http://localhost:8080/api/RequestTest

  

  這樣,spring mvc已經成功整合到了項目裏面!

5、Spring和Mybatis的配置

  稍歇片刻後,咱們繼續進行Mybatis和Spring組件的整合...

  先添加jdbc.properties(JDBC鏈接配置文件,固然這個文件裏面的內容直接寫到mybatis配置文件裏面也是能夠的)

  

  內容以下:

 1 #mysql
 2 jdbc.driverClassName=com.mysql.jdbc.Driver
 3 jdbc.url=jdbc\:mysql\://***.***.***\:3306/db_test?useSSL=false
 4 jdbc.username=username
 5 jdbc.password=password
 6 
 7 #c3p0鏈接池信息
 8 c3p0.minPoolSize=10
 9 c3p0.maxPoolSize=100
10 #當鏈接池中的鏈接耗盡的時候c3p0一次同時獲取的鏈接數
11 c3p0.acquireIncrement=3
12 #定義在從數據庫獲取新鏈接失敗後重復嘗試的次數
13 c3p0.acquireRetryAttempts=60
14 #兩次鏈接中間隔時間,單位毫秒
15 c3p0.acquireRetryDelay=1000
16 #鏈接關閉時默認將全部未提交的操做回滾
17 c3p0.autoCommitOnClose=false
18 #當鏈接池用完時客戶端調用getConnection()後等待獲取新鏈接的時間,超時後將拋出SQLException,如設爲0則無限
19 c3p0.checkoutTimeout=3000
20 #每120秒檢查全部鏈接池中的空閒鏈接。Default: 0
21 c3p0.idleConnectionTestPeriod=120
22 #最大空閒時間,60秒內未使用則鏈接被丟棄。若爲0則永不丟棄。Default: 0
23 c3p0.maxIdleTime=600
24 #若是設爲true那麼在取得鏈接的同時將校驗鏈接的有效性。Default: false
25 c3p0.testConnectionOnCheckin=false
26 #若是maxStatements與maxStatementsPerConnection均爲0,則緩存被關閉。Default: 0
27 c3p0.maxStatements=8
28 #maxStatementsPerConnection定義了鏈接池內單個鏈接所擁有的最大緩存statements數。Default: 0
29 c3p0.maxStatementsPerConnection=5
30 #自動超時回收Connection
31 c3p0.unreturnedConnectionTimeout=25
jdbc.properties

  繼續在resources文件夾裏面添加mybatis配置文件 spring-mybatis.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        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
 5 
 6     <bean id="configProperties" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
 7         <property name="locations">
 8             <list>
 9                 <value>classpath:jdbc.properties</value>
10             </list>
11         </property>
12     </bean>
13 
14     <!-- 配置數據源 -->
15     <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
16         <property name="driverClass" value="${jdbc.driverClassName}"/>
17         <property name="jdbcUrl" value="${jdbc.url}"/>
18         <property name="user" value="${jdbc.username}"/>
19         <property name="password" value="${jdbc.password}"/>
20         <property name="minPoolSize" value="${c3p0.minPoolSize}"/>
21         <property name="acquireIncrement" value="${c3p0.acquireIncrement}"/>
22         <property name="acquireRetryAttempts" value="${c3p0.acquireRetryAttempts}"/>
23         <property name="acquireRetryDelay" value="${c3p0.acquireRetryDelay}"/>
24         <property name="autoCommitOnClose" value="${c3p0.autoCommitOnClose}"/>
25         <property name="checkoutTimeout" value="${c3p0.checkoutTimeout}"/>
26         <property name="idleConnectionTestPeriod" value="${c3p0.idleConnectionTestPeriod}"/>
27         <property name="maxIdleTime" value="${c3p0.maxIdleTime}"/>
28         <property name="testConnectionOnCheckin" value="${c3p0.testConnectionOnCheckin}"/>
29         <property name="maxStatements" value="${c3p0.maxStatements}"/>
30         <property name="maxStatementsPerConnection" value="${c3p0.maxStatementsPerConnection}"/>
31         <property name="unreturnedConnectionTimeout" value="${c3p0.unreturnedConnectionTimeout}"/>
32     </bean>
33 
34     <!-- 配置mybatisSqlSessionFactoryBean -->
35     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
36         <property name="dataSource" ref="dataSource"/>
37         <property name="mapperLocations" value="classpath:mapper/*.xml"/>
38     </bean>
39     <!-- 配置mybatis mapper接口 -->
40     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
41         <property name="basePackage" value="Dao"/>
42         <!--<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>-->
43     </bean>
44 
45     <!-- 配置事務管理器 -->
46     <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
47         <property name="dataSource" ref="dataSource"/>
48     </bean>
49 
50 </beans>
spring-mybatis.xml

  添加spring支持(applicationContext.xml),並在spring支持裏面將mybatis配置文件進行引入

  內容以下:

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans
 3         xmlns="http://www.springframework.org/schema/beans"
 4         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 5         xmlns:context="http://www.springframework.org/schema/context"
 6         xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
 7 
 8     <context:annotation-config />
 9     <!-- 配置component所在的包,自動加載須要管理的Bean -->
10     <context:component-scan base-package="Service,Dao" />
11     <import resource="spring-mybatis.xml" />
12 </beans>

  applicationContext.xml配置文件是對spring的配置,咱們配置spring組件的掃描包圍Service和Dao層目錄,而後將spring-mybatis.xml配置文件導入.

  完成這三個後的文件目錄是這樣子的:

  

  target文件夾是剛纔編譯運行時候自動產生的,不要驚慌~~~

  完成這幾步後,咱們還須要將spring的配置加載到已有的框架中去,打開web.xml文件,進行添加spring配置

  在剛纔的web-app標籤內繼續添加spring支持:

  

  此刻完整的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 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 5          xmlns="http://java.sun.com/xml/ns/javaee"
 6          xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
 7          version="3.0">
 8   <display-name>Archetype Created Web Application</display-name>
 9   <welcome-file-list>
10     <welcome-file>/index.jsp</welcome-file>
11   </welcome-file-list>
12   <!-- Spring MVC配置 -->
13   <servlet>
14     <servlet-name>spring</servlet-name>
15     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
16     <!--Spring-servlet.xml config-->
17     <init-param>
18       <param-name>contextConfigLocation</param-name>
19       <param-value>classpath:spring-servlet.xml</param-value>
20     </init-param>
21     <!-- load-on-startup元素標記容器是否在啓動的時候就加載這個servlet(實例化並調用其init()方法) -->
22     <load-on-startup>1</load-on-startup>
23   </servlet>
24   <servlet-mapping>
25     <servlet-name>spring</servlet-name>
26     <url-pattern>/</url-pattern>
27   </servlet-mapping>
28 
29   <!--spring listener config-->
30   <context-param>
31     <param-name>contextConfigLocation</param-name>
32     <param-value>classpath:applicationContext.xml</param-value>
33   </context-param>
34   <listener>
35     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
36   </listener>
37 
38   <!-- 配置log4j配置文件的路徑,能夠是xml或 properties(此參數必須配)-->
39   <!--<context-param>-->
40   <!--<param-name>log4jConfigLocation</param-name>-->
41   <!--<param-value>classpath:log4j.properties</param-value>-->
42   <!--</context-param>-->
43 
44 </web-app>
web.xml

  到此刻,咱們的spring、mybatis已經整合完畢,接下來稍歇片刻,咱們進行demo的完成。

6、demo的構建

   打開數據庫,咱們新建一個數據庫,並設計兩張測試表,student和studentclass

  

  student表的設計以下:

  

-- ----------------------------
-- Table structure for `student`
-- ----------------------------
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
  `Uid` binary(36) NOT NULL COMMENT 'Uid',
  `Name` varchar(20) NOT NULL,
  `Age` int(3) NOT NULL,
  `ClassId` int(3) NOT NULL,
  PRIMARY KEY (`Uid`),
  KEY `StudentClass` (`ClassId`),
  CONSTRAINT `StudentClass` FOREIGN KEY (`ClassId`) REFERENCES `studentclass` (`ClassId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

  studentclass表的設計以下:

  

-- ----------------------------
-- Table structure for `studentclass`
-- ----------------------------
DROP TABLE IF EXISTS `studentclass`;
CREATE TABLE `studentclass` (
  `ClassId` int(3) NOT NULL AUTO_INCREMENT,
  `ClassName` varchar(10) DEFAULT NULL,
  PRIMARY KEY (`ClassId`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

  將數據庫建好後,咱們進行Entity,Dao,Service層以及mapper文件的的編寫。

  首先在mapper文件夾新建一個mapper文件:StudentMapper.xml

  1 <?xml version="1.0" encoding="UTF-8"?>
  2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3 <mapper namespace="Dao.StudentMapper">
  4     <resultMap id="BaseResultMap" type="Entity.Student">
  5         <id column="Uid" jdbcType="BINARY" property="uid" />
  6         <result column="Name" jdbcType="VARCHAR" property="name" />
  7         <result column="Age" jdbcType="INTEGER" property="age" />
  8         <result column="ClassId" jdbcType="INTEGER" property="classid" />
  9     </resultMap>
 10     <sql id="Base_Column_List">
 11         Uid, Name, Age, ClassId
 12     </sql>
 13     <select id="selectByPrimaryKey" parameterType="byte[]" resultMap="BaseResultMap">
 14         select
 15         <include refid="Base_Column_List" />
 16         from student
 17         where Uid = #{uid,jdbcType=BINARY}
 18     </select>
 19     <select id="selectByCondition" parameterType="Entity.Student" resultMap="BaseResultMap">
 20         SELECT
 21         <include refid="Base_Column_List"/>
 22         from student
 23         <where>
 24             1=1
 25             <if test="uid != null">
 26                 and Uid=#{uid,jdbcType=BINARY}
 27             </if>
 28             <if test="name != null">
 29                 and Name=#{name,jdbcType=VARCHAR}
 30             </if>
 31             <if test="age != null">
 32                 and Age=#{age,jdbcType=INTEGER}
 33             </if>
 34             <if test="classid != null">
 35                 and ClassId=#{classid,jdbcType=INTEGER}
 36             </if>
 37         </where>
 38     </select>
 39     <delete id="deleteByPrimaryKey" parameterType="byte[]">
 40         delete from student
 41         where Uid = #{uid,jdbcType=BINARY}
 42     </delete>
 43     <insert id="insert" parameterType="Entity.Student">
 44         insert into student (Uid, Name, Age,
 45         ClassId)
 46         values (#{uid,jdbcType=BINARY}, #{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER},
 47         #{classid,jdbcType=INTEGER})
 48     </insert>
 49     <insert id="insertSelective" parameterType="Entity.Student">
 50         insert into student
 51         <trim prefix="(" suffix=")" suffixOverrides=",">
 52             <if test="uid != null">
 53                 Uid,
 54             </if>
 55             <if test="name != null">
 56                 Name,
 57             </if>
 58             <if test="age != null">
 59                 Age,
 60             </if>
 61             <if test="classid != null">
 62                 ClassId,
 63             </if>
 64         </trim>
 65         <trim prefix="values (" suffix=")" suffixOverrides=",">
 66             <if test="uid != null">
 67                 #{uid,jdbcType=BINARY},
 68             </if>
 69             <if test="name != null">
 70                 #{name,jdbcType=VARCHAR},
 71             </if>
 72             <if test="age != null">
 73                 #{age,jdbcType=INTEGER},
 74             </if>
 75             <if test="classid != null">
 76                 #{classid,jdbcType=INTEGER},
 77             </if>
 78         </trim>
 79     </insert>
 80     <update id="updateByPrimaryKeySelective" parameterType="Entity.Student">
 81         update student
 82         <set>
 83             <if test="name != null">
 84                 Name = #{name,jdbcType=VARCHAR},
 85             </if>
 86             <if test="age != null">
 87                 Age = #{age,jdbcType=INTEGER},
 88             </if>
 89             <if test="classid != null">
 90                 ClassId = #{classid,jdbcType=INTEGER},
 91             </if>
 92         </set>
 93         where Uid = #{uid,jdbcType=BINARY}
 94     </update>
 95     <update id="updateByPrimaryKey" parameterType="Entity.Student">
 96         update student
 97         set Name = #{name,jdbcType=VARCHAR},
 98         Age = #{age,jdbcType=INTEGER},
 99         ClassId = #{classid,jdbcType=INTEGER}
100         where Uid = #{uid,jdbcType=BINARY}
101     </update>
102 </mapper>

  以上這段代碼是直接使用mybatis generator直接進行生成的,若是不想手寫的話(手寫容易出錯),能夠直接使用該工具進行生成,該工具的下載以及使用參見本人博客地址:http://www.cnblogs.com/7tiny/p/7597315.html

  添加Entity實體

  

 1 package Entity;
 2 
 3 public class Student {
 4     private byte[] uid;
 5 
 6     private String name;
 7 
 8     private Integer age;
 9 
10     private Integer classid;
11 
12     public byte[] getUid() {
13         return uid;
14     }
15 
16     public void setUid(byte[] uid) {
17         this.uid = uid;
18     }
19 
20     public String getName() {
21         return name;
22     }
23 
24     public void setName(String name) {
25         this.name = name == null ? null : name.trim();
26     }
27 
28     public Integer getAge() {
29         return age;
30     }
31 
32     public void setAge(Integer age) {
33         this.age = age;
34     }
35 
36     public Integer getClassid() {
37         return classid;
38     }
39 
40     public void setClassid(Integer classid) {
41         this.classid = classid;
42     }
43 }

  在Dao層寫Mybatis接口(不須要寫實現類,mybatis不須要),新建StudentMapper

  

 1 package Dao;
 2 
 3 import Entity.Student;
 4 import org.springframework.stereotype.Repository;
 5 
 6 import java.util.List;
 7 
 8 @Repository
 9 public interface StudentMapper {
10     int deleteByPrimaryKey(byte[] uid);
11 
12     int insert(Student record);
13 
14     int insertSelective(Student record);
15 
16     Student selectByPrimaryKey(byte[] uid);
17 
18     List<Student> selectByCondition(Student record);
19 
20     int updateByPrimaryKeySelective(Student record);
21 
22     int updateByPrimaryKey(Student record);
23 }

  在Service層寫對Dao層的訪問邏輯,固然Demo沒有什麼業務處理邏輯,僅做爲Demo

  

  IStudentService 接口:

 1 package Service;
 2 
 3 import Entity.Student;
 4 
 5 import java.util.List;
 6 
 7 public interface IStudentService {
 8     int deleteByPrimaryKey(byte[] uid);
 9 
10     int insert(Student record);
11 
12     int insertSelective(Student record);
13 
14     Student selectByPrimaryKey(byte[] uid);
15 
16     List<Student> selectByCondition(Student record);
17 
18     int updateByPrimaryKeySelective(Student record);
19 
20     int updateByPrimaryKey(Student record);
21 }

  StudentService 實現了 IStudentService 接口:

 1 package Service;
 2 
 3 import Dao.StudentMapper;
 4 import Entity.Student;
 5 import org.springframework.beans.factory.annotation.Autowired;
 6 import org.springframework.stereotype.Service;
 7 
 8 import java.util.List;
 9 
10 @Service
11 public class StudentService implements IStudentService {
12     @Autowired
13     private StudentMapper studentMapper;
14 
15     @Override
16     public int deleteByPrimaryKey(byte[] uid) {
17         return studentMapper.deleteByPrimaryKey(uid);
18     }
19 
20     @Override
21     public int insert(Student record) {
22         return studentMapper.insert(record);
23     }
24 
25     @Override
26     public int insertSelective(Student record) {
27         return studentMapper.insertSelective(record);
28     }
29 
30     @Override
31     public Student selectByPrimaryKey(byte[] uid) {
32         return studentMapper.selectByPrimaryKey(uid);
33     }
34 
35     @Override
36     public List<Student> selectByCondition(Student record) {
37         return studentMapper.selectByCondition(record);
38     }
39 
40     @Override
41     public int updateByPrimaryKeySelective(Student record) {
42         return studentMapper.updateByPrimaryKeySelective(record);
43     }
44 
45     @Override
46     public int updateByPrimaryKey(Student record) {
47         return studentMapper.updateByPrimaryKey(record);
48     }
49 }

  而後咱們寫一個StudentController用於調用Service

   

 1 package Controllers;
 2 
 3 import Entity.Student;
 4 import Service.IStudentService;
 5 import org.springframework.beans.factory.annotation.Autowired;
 6 import org.springframework.web.bind.annotation.GetMapping;
 7 import org.springframework.web.bind.annotation.RequestMapping;
 8 import org.springframework.web.bind.annotation.RestController;
 9 
10 import java.util.List;
11 
12 @RestController
13 @RequestMapping("/api/Student")
14 public class StudentController {
15     @Autowired
16     private IStudentService service;
17 
18     @GetMapping()
19     public String Get() {
20         List<Student> students = service.selectByCondition(new Student());
21         String jsonResult = com.alibaba.fastjson.JSON.toJSONString(students);
22         return jsonResult;
23     }
24 }

  走到這一步的代碼目錄結構是這樣子的:

  

  若是進行順利的話,咱們運行咱們的Tomacat服務器,並調用咱們的新接口:http://localhost:8080/api/Student

  運行時候,別忘記了修改jdbc.properties文件裏的鏈接url以及用戶名密碼!!!

  

  

  哇,數據成功顯示!(別把這個數據當成你會真的顯示出來的同樣,這是我數據庫原有的數據,哈哈哈)

  

  還不快去添加幾條數據調用一下試試嘛~

7、結尾

  至此,咱們的SSM框架已經基本搭建完畢,咱們已經用咱們搭建的Demo從真實的數據庫中獲取到了數據,並轉成了Json格式,在瀏覽器中用Rest api接口的形式獲取到了。

  該項目源代碼能夠在Github上找到,若是須要的能夠直接去下載->

  https://github.com/sevenTiny/Demo.SSM (不趕忙訪問點個Star嘛?)

  若是在搭建中還有任何疑問,隨時能夠在下面的簽名聯繫方式中找到我~ 茫茫人海中,也是有緣~~~

  若是有推薦工做的也能夠在下面的聯繫方式中找到我哦,若是是這樣的話,我是真的感激呢!!!~~~

相關文章
相關標籤/搜索