Spring、SpringMVC、Mybatis整合之工程的搭建

SSM框架整合之環境配置部分前端

學習完了Spring、SpringMVC、Mybatis框架,咱們就能夠嘗試系統將三者進行整合。整合並不複雜,咱們只須要實現最基礎的配置,便可輕鬆的掌握SSM框架是如何實際項目中使用的。 基於上一篇博文:maven起步,咱們應該知道了如何搭建maven項目,那麼在此基礎上,手把手教你搭建Spring、SpringMVC、Mybatis框架的環境。java

源碼請 點擊這裏 前往個人GitHub。mysql

<!--more-->git

關於項目

項目環境

項目框架:後端:spring+mybatis+springmvc; 前端:bootstrap+Font Awesome圖標集
測試環境:IDEA+tomcat7+mysql5.7+jdk8+maven
數據庫名稱:ssm

項目功能

1. 用戶登陸
2. 客戶信息的增、刪、改、查
3. 客戶信息的列表展現和分頁查詢功能

項目結構

備註 如上這是一個標準的maven項目(對maven項目的搭建有不懂的能夠查看個人博文:maven起步github

img: 放了一些README.md文檔所須要得圖片,沒有實際意義。web

controller: web層,存放springmvc的相關控制器類。spring

mapper: 存放接口和映射文件。由於本項目採用了mybatis的接口開發,因此須要將接口和映射文件放在同一目錄下,而且名稱相同。sql

pojo: 存放Java的實體類數據庫

service: 業務層,用於存放一些業務層代碼。json

不要奇怪爲何沒有出現Dao層,由於本項目相對簡單,並無多複雜的邏輯,因此也就必要再寫一個Dao層進行擴展。

resources: 是maven項目存放配置文件的根目錄,在本例中包含兩個子文件夾:resourcespring。前者是存放一些如logback.properties的配置文件;後者是存放spring的配置文件(spring和springmvc)。

my.sql: 存放了關於項目數據庫建立和表建立的SQL語句。

fonts: 存放一些字體的配置文件。爲了頁面的美感,咱們採用了Awesome圖標集。

lib: 包含了項目中用到的一些前端類庫。

page: 包含全部前端頁面。

整合思路

繼上一篇博文:Spring MVC起步其實咱們已經瞭解瞭如何整合Spring和Spring MVC框架。那麼,接下來咱們就須要瞭解如何在此基礎上整合Mybatis框架。 首先須知Mybatis框架是一個持久層框架,而Spring MVC是WEB層框架,Spring框架則充當着業務層的角色。那麼將三者聯繫起來正好組成了web--service--dao的三層架構體系。那麼整合思路就以下所示了:

  1. 整合dao(即mapper),實現Mybatis和Spring的整合
  2. 整合service,由Spring管理service接口,在service中能夠調用dao(mapper)
  3. 整合web(controller),實現Spring MVC和Spring的整合,在controller中調用service

jar依賴

<dependencys>
    <!-- 單元測試 -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
    </dependency>

    <!-- 1.日誌 -->
    <dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-classic</artifactId>
      <version>1.1.1</version>
    </dependency>

    <!-- 2.數據庫 -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.37</version>
      <scope>runtime</scope>
    </dependency>
    <dependency>
      <groupId>c3p0</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.1.2</version>
    </dependency>

    <!-- DAO: MyBatis -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.3.0</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.2.3</version>
    </dependency>

    <!-- 3.Servlet web -->
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.5.4</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
    </dependency>

    <!-- 4.Spring -->
    <!-- 1)Spring核心 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>4.1.7.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>4.1.7.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>4.1.7.RELEASE</version>
    </dependency>
    <!-- 2)Spring DAO層 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>4.1.7.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>4.1.7.RELEASE</version>
    </dependency>
    <!-- 3)Spring web -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>4.1.7.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>4.1.7.RELEASE</version>
    </dependency>
    <!-- 4)Spring test -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>4.1.7.RELEASE</version>
    </dependency>
  </dependencies>

以上是SSM框架最基本的依賴配置,不少時候項目中的報錯是由於jar包衝突,爲避免儘可能採用同一版本的jar依賴。

注: 由於本項目使用的是IDEA,咱們還須要在pom.xml中寫入如下配置,以便IDEA可以檢測到maven工程非resources目錄下的配置文件

<build>
    <finalName>ssm</finalName>
    <resources>
      <resource>
        <directory>${basedir}/src/main/java</directory>
        <includes>
          <include>**/*.properties</include>
          <include>**/*.xml</include>
        </includes>
      </resource>
      <resource>
        <directory>${basedir}/src/main/resources</directory>
      </resource>
    </resources>
</build>

XML配置文件

jdbc.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm_paging?useUnicode=true&characterEncoding=UTF-8
jdbc.username=用戶名
jdbc.password=密碼

把數據庫信息單獨提取到一個文件中,在XML中先使用<context:property-placeholder>加載配置文件,而後使用${jdbc.xx}的格式調用便可。

注意:在jdbc.url屬性中對應的數據庫連接要規定字符編碼爲UTF-8,由於我遇到的狀況就是我在建立數據庫和表的時候都指定了字符集,可是前臺保存進來的數據仍是會亂碼,就是項目在連接數據庫時沒有指定字符編碼的緣由

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<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_2_5.xsd"
         id="WebApp_ID" version="2.5">

    <display-name>Archetype Created Web Application</display-name>
    <welcome-file-list>
        <welcome-file>/WEB-INF/index.jsp</welcome-file>
    </welcome-file-list>

    <!-- 配置spring的字符編碼過濾器,保證request請求的中文字符不會亂碼(注意這個過濾器要放到最前面) -->
    <filter>
        <filter-name>CharacterEncoding</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>utf-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncoding</filter-name>
        <!-- 設置這個字符編碼過濾器做用與每個請求 -->
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!-- 配置Spring的servlet監聽器 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!-- 加載spring容器 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring/beans.xml</param-value>
    </context-param>

    <!-- 配置springmvc的前端控制器,request請求會先通過這個控制器 -->
    <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- 同時加載Spring MVC的配置文件。request通過了前端控制器接下來就根據映射器判斷該請求須要走哪一個控制器 -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring/springmvc.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <!-- *.do 表示咱們請求映射路徑後綴爲.do,  咱們也能夠設置爲/ -->
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
</web-app>

web.xml中的配置主要是三方面:

  1. 配置Spring的字符編碼過濾器:CharacterEncodingFilter(防止request請求中文亂碼)。
  2. 配置Spring的servlet監聽器:ContextLoaderListener,告訴Spring須要加載那哪些配置文件來完成Spring的上下文。配置文件經過contextConfigLocation指定。
  3. 配置Spring MVC的前端控制器(全部的request請求都會先通過這個前端控制器)。

beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 配置註解掃描 -->
    <context:component-scan base-package="cn.tycoding.service"/>

    <!-- 加載配置文件 -->
    <context:property-placeholder location="classpath:resource/jdbc.properties"/>

    <!-- 數據庫鏈接池 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <!-- 配置鏈接池屬性 -->
        <property name="driverClass" value="${jdbc.driver}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>

        <!-- c3p0鏈接池的私有屬性 -->
        <property name="maxPoolSize" value="30" />
        <property name="minPoolSize" value="10" />
        <!-- 關閉鏈接後不自動commit -->
        <property name="autoCommitOnClose" value="false" />
        <!-- 獲取鏈接超時時間 -->
        <property name="checkoutTimeout" value="10000" />
        <!-- 當獲取鏈接失敗重試次數 -->
        <property name="acquireRetryAttempts" value="2" />
    </bean>

    <!-- 配置SqlSessionFactory對象 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 注入數據庫鏈接池 -->
        <property name="dataSource" ref="dataSource"/>
        <!-- 掃描pojo包,使用別名配置(在mybatis中可使用別名,即pojo的名稱) -->
        <property name="typeAliasesPackage" value="cn.tycoding.pojo"/>
        <!-- 掃描mapper的配置文件 -->
        <property name="mapperLocations" value="classpath:cn/tycoding/mapper/*.xml"/>
        <!--也能夠引入mybatis配置文件 -->
        <!--<property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml"/>-->
    </bean>

    <!-- 使用mybatis的接口代理開發模式(必須保證接口和對應的mybatis的xml名稱相同,且在一個文件夾內) -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="cn.tycoding.mapper"/>
        <!--<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>-->
    </bean>
</beans>

備註: 本例中beans.xml主要配置兩塊內容:1.鏈接池;2.Mybatis-Spring的配置 (固然可能這並不很標準,例如一些事物管理器,在這裏我並無配置;一樣,你還能夠將相關的Mybatis的配置提取出來,只要在最後web.xml中加載這個配置文件就能夠了。

SqlSessionFactoryBean

Spring框架簡化數據庫訪問的方式之一就是管理數據庫鏈接的聲明週期和ORM框架的Session,以確保他們正常的打開和關閉。而在mybatis-spring中,SqlSessionFactoryBean實現了Spring的FactoryBean接口,用於建立SqlSessionFactory

  • dataSource是必要的配置,上面咱們僅僅是寫了數據源配置,接下來的數據庫訪問對象確定要使用這個數據源來獲取連接對象,因此必須指定數據源。
  • typeAliases則是啓用別名配置,typeAliasesPackage則會爲pojo包下的全部類對象都配置別名,當咱們在對應的XML映射中指定ResultType等時,就能夠直接寫pojo的類名,而不須要寫全限定名。
  • mapperLocations: 用於指定Mapper的XML文件位置(對於那種Mapper接口和XML配置同名且在同一個配置文件夾下,Mybatis其實會根據Mapper的Class文件自動找對應的XML配置文件,可是這裏我建議寫上)。
  • configLocation: 用於指定mybatis的配置文件位置,由於本項目中並無涉及太多複雜的邏輯,因此這裏我就沒有特地配置mybatis的config。

MapperScannerConfigurer

在瞭解MapperScannerConfigurer以前咱們須要瞭解一下MapperFactoryBean,Mybatis-Spring提供了一個動態代理的實現:MapperFactoryBean,他能實現將映射器接口(由於代理建立在運行環境中,那麼指定的映射器必須是接口而不是實現類)直接注入到service的Bean中。這樣經過代理對象去建立編寫數據訪問對象,從而代替SqlSessionTepmlate等工具。 可是在Mybatis-Spring中還提供了一個轉換器MapperScannerConfigurer,它會查找類路徑下的映射器(接口)並自動將他們建立成MapperFactoryBean。經過將接口轉換成Spring容器中的Bean,在Service層直接注入接口便可,這樣大大簡化了Dao層實例的編寫。 basePackage正是指定接口的位置。 注意咱們這裏並不須要指定SqlSessionFactory(即咱們註釋掉的部分),由於使用MapperScannerConfigurer會建立MapperFactoryBean後自動裝配(XML配置)。可是若是存在多個dataSource,該自動裝配可能就會失效,這時咱們必須使用sqlSessionFacoryBeanName來指定引用哪一個bean

beans.xml配置階段算是基本告一段落,咱們回想一下:在沒有使用Mybatis前咱們使用Spring提供的JDBC模板來訪問數據庫,咱們發現這種方式代碼量特別大,並且於Java代碼的耦合性也比較大,Mybatis則正好彌補了這些缺點,它使用的XML配置更加的小巧方便且支持原生SQL的編寫。 Mybatis-Spring提供了移動動態代理的方式來代替手工的SqlSessionTemplate編寫數據庫訪問對象,咱們只須要編寫一個接口,經過在Mapper對應的XML中直接寫SQL就能夠進行數據庫訪問。固然咱們必須配置SqlSessionFactoryBeanMapperScannerConfigurer

springmvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
         http://www.springframework.org/schema/aop/spring-aop.xsd
         http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context.xsd
         http://www.springframework.org/schema/tx
         http://www.springframework.org/schema/context/spring-tx.xsd
         http://www.springframework.org/schema/mvc
         http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!-- 開啓註解掃描 -->
    <context:component-scan base-package="com.TyCoding.controller"/>

    <!-- 配置springmvc的基本控制器,並開啓了對json數據格式的支持 -->
    <mvc:annotation-driven/>

    <!-- 配置springmvc的視圖解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

在博文初識Spring MVC咱們已經對SpringMVC有了必定的瞭解。那麼在這裏咱們回顧一下SpringMVC的架構設計: 那麼SpringMVC的XML無非就是:

  1. 配置SpringMVC前端控制器。
  2. 配置SpringMVC的基本控制器(處理請求的Spring組件)。
  3. 配置視圖解析器。

因此:

  1. 首先在web.xml中配置SpringMVC的前端控制器:DispatcherServlet
  2. springmvc.xml中配置SpringMVC的基本控制器:<mvc:annotation-driven>(註解驅動方式)。
  3. 開啓註解掃描:<context:component-scan>,主要掃描Controller層的註解(由於SpringMVC是web層框架)。
  4. 配置SpringMVC的視圖解析器:InternalResourceViewResolver,用於當Controller處理完請求後將處理後的數據結果返回給視圖層(JSP等)。

配置pojo和sql

pojo

在項目pojo文件夾下建立User.javaCustomer.java以及PageBean.java 1.User

//用戶id
private int uid;
//用戶登陸名
private String username;
//用戶密碼
private String password;
...
getter/setter方法省略

2.Customer

//客戶的id
private int c_id;
//客戶的姓名
private String c_name;
//客戶的電話
private String c_telephone;
//客戶的住址
private String c_address;
//客戶備註
private String c_remark;
...
getter/setter方法省略

3.PageBean PageBean爲實現分頁瘋轉給的JavaBean,詳細字段屬性請查看註釋。

public class PageBean<T> implements Serializable {
    //當前頁
    private int pageCode;

    //總頁數=總條數/每頁顯示的條數
    private int totalPage;

    //總記錄數
    private int totalCount;

    //每頁顯示的記錄條數
    private int pageSize;

    //每頁顯示的數據
    private List<T> beanList;
}

這裏用了自定義泛型類<T>就是實現由後臺決定這個分頁Bean要去封裝那種類型的數據,咱們調用時傳入類型就會封裝什麼類型數據。好比咱們須要對Customer分頁,在調用這個類是就寫new PageBean<Customer>()。那麼數據就會強制綁定爲這個Customer類的數據。

sql

建立數據庫並編寫項目所須要的表結構,寫入測試數據。

create database ssm character set utf8;
use ssm;

create table user(
    uid int primary key auto_increment,
    username varchar(100),
    password varchar(100)
) default charset = utf8;

create table customer(
    c_id int primary key auto_increment,
    c_name varchar(100),
    c_telephone varchar(100),
    c_address varchar(100),
    c_remark varchar(100)
) default charset = utf8;

# 插入數據
insert into user values(1,'admin','admin');

insert into customer values(1,'塗陌','123456789','你猜','不想寫備註');
insert into customer values(2,'逗瓜','123456789','你猜','不想寫備註');
insert into customer values(3,'憤青','123456789','你猜','不想寫備註');
insert into customer values(4,'鹹魚','123456789','你猜','不想寫備註');
insert into customer values(5,'小白','123456789','你猜','不想寫備註');
insert into customer values(6,'菜雞','123456789','你猜','不想寫備註');

綜上

到目前爲止咱們已經完成了Spring、SpringMVC、Mybatis的基本配置,並建立了項目所需的實體類以及數據庫表。 最後咱們須要將該項目部署到Tomcat服務器上。若是配置正確,那麼在瀏覽器上回彈出index頁面。

<br/>

交流

若是你們有興趣,歡迎你們加入個人Java交流羣:671017003 ,一塊兒交流學習Java技術。博主目前一直在自學JAVA中,技術有限,若是能夠,會盡力給你們提供一些幫助,或是一些學習方法,固然羣裏的大佬都會積極給新手答疑的。因此,別猶豫,快來加入咱們吧!

<br/>

聯繫

If you have some questions after you see this article, you can contact me or you can find some info by clicking these links.

相關文章
相關標籤/搜索