1. 程式人生 > >Maven整合SSM框架(maven+spring+springmvc+mybatis)

Maven整合SSM框架(maven+spring+springmvc+mybatis)

啊哈,終於到了用Maven整合SSM這個撲街含家產了。弄了整整一天才跑通。Mybatis的配置有些繁瑣,跟之前學習的那個有點出去,加上Eclipse的Spring工具沒有弄,配置的時候沒有提示被搞蒙圈了。不過萬幸,最終還是憑藉我高超的只會完成了!!哈哈哈

專案原始碼地址
走過路過的朋友幫忙點歌star☆ ^_^

一:準備材料

Eclipse+Maven+jdk+Tomcat,安裝不多說了。

二:Eclipse新建Maven專案

File->New->MavenProject->maven-archetype-webapp

Group Id: com
.bigname Artifacrt Id: MavenDemo01

三:構建目錄結構

建立自己喜歡的目錄結構,體現架構思想
這裡寫圖片描述

四:新增依賴

1:依賴SpringMVC

a.宣告依賴,此時jar包會自動下載

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>4.3.14.RELEASE</version>
</dependency
>

b.建立配置檔案:
在resource下建立spring-mvc.xml,內容如下

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">
<!-- 開啟註解 --> <mvc:annotation-driven /> <!-- 讓掃描spring掃描這個包下所有的類,讓標註spring註解的類生效 --> <context:component-scan base-package="com.bigname.demo03.controller"></context:component-scan> <!-- 檢視解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/views/" /> <property name="suffix" value=".jsp"></property> </bean> </beans>

c.在web.xml中新增配置

 <!-- 定義前端控制器 -->
  <servlet>
    <servlet-name>spring-mvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!-- 指定路徑 -->
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring-mvc.xml</param-value>
    </init-param>
    <!-- 隨spring啟動而啟動 -->
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>spring-mvc</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>

這個時候可以新建一個controller來檢驗一下請求是否能走通,成功了再執行下一步。

2:依賴spring

由於在依賴springmvc的時候已經添加了許多spring相關包了,所以此時不需要新增額外的包,可以直接建立配置檔案了。

a.建立配置檔案spring-context.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:p="http://www.springframework.org/schema/p"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:util="http://www.springframework.org/schema/util"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation=
            "
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd  
            http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd  
            http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.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
            "
            > 

</beans>  

b.在web.xml中配置spring

<!-- 配置介面卡spring -->
  <listener>
    <description>啟動spring容器</description>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring-context.xml</param-value>
  </context-param>  

此時spring已經配置完成

3.依賴c3p0

需要依賴jar包

  • c3p0
  • jdbc-mysql

a.在pom.xml中新增依賴宣告

<!-- c3p0 資料庫連線池 -->
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.2</version>
        </dependency>

        <!-- 資料庫 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>6.0.6</version>
        </dependency>

b.在spring-context.xml配置c3p0

<!-- 配置c3p0 -->
    <!-- 連線池 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql://localhost/test?characterEncoding=utf8&amp;serverTimezone=UTC"></property>
        <property name="user" value="root"></property>
        <property name="password" value="root"></property>
        <property name="minPoolSize" value="1"></property>
        <property name="maxPoolSize" value="5"></property>
        <property name="initialPoolSize" value="1"></property>
        <property name="acquireIncrement" value="1"></property>
    </bean>
4.配置spring宣告式事務管理

需要依賴jar包

  • spring-tx
  • spring-jdbc

a.在pom.xml中生命依賴

<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>4.3.14.RELEASE</version>
        </dependency>


        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.3.14.RELEASE</version>
        </dependency>

b.在spring-context.xml配置
如果tx這些爆紅,則需要檢查該檔案頭部資訊是否完整。可以往上翻檢視spring-context.xml

<!-- 配置事務管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!-- 使用註解來控制事務 -->
    <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
5:依賴Mybatis

這裡共依賴四個jar包

  • mybatis、
  • mybatis-spring整合
  • pagehelper分頁、
  • cglib代理

a.在pom.xml中新增依賴宣告

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.1</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.0</version>
        </dependency>

        <!--  分頁助手 -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>5.1.2</version>
        </dependency>

        <!-- 代理 -->
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>3.2.2</version>
        </dependency>

b.新建mybatis配置檔案mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <settings>
        <setting name="cacheEnabled" value="true"/>
        <setting name="defaultStatementTimeout" value="3000"/>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <!-- 代理 -->
        <setting name="proxyFactory" value="CGLIB"/>
        <setting name="lazyLoadingEnabled" value="true"/>
    </settings>

    <!-- 分頁外掛 -->
    <plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor">
            <!-- 該引數預設為false
            設定為true時,會將RowBounds第一個引數offset當成pageNum頁碼使用
            和startPage中的pageNum效果一樣 -->
            <property name="offsetAsPageNum" value="true"/>
            <!-- 該引數預設為false
            設定為true是,使用RowBounds分頁會進行count查詢 -->
            <property name="rowBoundsWithCount" value="true"/>
            <!-- 設定為true時,如果pageSize=0或者ROwRounds.limit=0就會查詢出全部的結果
            (相當於每一偶執行分頁查詢,但是返回結果仍然是page型別) -->
            <property name="pageSizeZero" value="true"/>
        </plugin>
    </plugins>

</configuration>

這次曾出現一個問題,在程式執行的時候檢驗不通過,因為之前按照教程的寫法是:

        <plugin interceptor="com.github.pagehelper.PageHelper">
        <property name="dialect" value="mysql"/>

然後報了型別轉換的異常,最後查網上的資料改成現在的樣子就成功了。

c.在spring-context.xml中配置mybatis
這裡要繫結資料來源、指明配置檔案位置、mapper位置、掃描dao層

<!-- 配置mybatis, 繫結c3p0-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="configLocation" value="classpath:mybatis-config.xml"></property>
        <property name="mapperLocations">
            <list>
                <value>classpath:mapper/*.xml</value>
            </list>
        </property>
    </bean>

    <!-- 掃描生成所有dao層 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.bigname.demo03.dao"></property>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
    </bean>

—-

至此maven已經成功整合了spring+springmvc+mybatis,接下來整合測試一遍

1.建立資料庫test、表格Member

id name password
1 樑世傑 123
2 劉德華 456
3 周潤發 789
4 shijie 123

2.core層建立實體類
要與資料庫欄位對應

package com.bigname.demo03.core;

public class Member {
    private int id;
    private String name;
    private String password;
    public Member(){}
    public Member(int id, String name, String password) {
        super();
        this.id = id;
        this.name = name;
        this.password = password;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    @Override
    public String toString() {
        return "Member [id=" + id + ", name=" + name + ", password=" + password
                + "]";
    }

}

3.dao層建立資料訪問類
a.建立介面

public interface MemberDao {
    Member selectMemberByName(@Param("name")String name)throws Exception;
}

b.建立MemberDaoMapper.xml
這裡出現過一個問題,當傳入中文時發生過異常,應為其中的#號之前攜程$符號了,另外a中需要增加@Param的註解來說明是屬性的意思

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.bigname.demo03.dao.MemberDao">
    <select id="selectMemberByName" resultType="com.bigname.demo03.core.Member" parameterType="string">
        select * from Member where name = #{name}
    </select>
</mapper>

然後只要得到MemberDao的物件就能夠訪問資料庫啦

4.function建立業務類
a.建立Member業務介面

package com.bigname.demo03.function;

@Service
public interface IMemberFunction {
    Member login(String name, String passsword) throws Exception;
}

b.建立Member業務介面實現類

package com.bigname.demo03.function;

@Service
public class MemberFunctionImpl implements IMemberFunction{
    @Autowired
    MemberDao mDao;

    public Member login(String name, String passsword) throws Exception {
        System.out.println(name + passsword);
        if(StringUtil.isNullOrZero(name)){
            System.out.println("使用者名稱不能為空");
            return null;
        }
        if(StringUtil.isNullOrZero(passsword)){
            System.out.println("密碼不能為空");
            return null;
        }
        Member member = mDao.selectMemberByName(name);
        return member;
    }

}

5.建立LoginController,定義介面

package com.bigname.demo03.controller;
@Controller
public class LoginController {
    @Autowired
    IMemberFunction iMemberFunc;

    @RequestMapping(value = "/hello")
    public String hello(){
        System.out.println("接收到請求 ,Hello");
        return "hi";
    }

    @RequestMapping(value = "/login")
    public String login(String name, String password){
        try {
            Member member = iMemberFunc.login(name, password);
            if(member == null){
                System.out.println("登陸失敗");
            }else {
                System.out.println("登陸成功");
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println(e.getMessage());
            System.out.println("登入失敗");
        }
        return null;
    }
}

在配置springmvc的時候如果成功了,那麼hello.do這個介面就能正常使用的了。

另外:spring要掃描function層,springmvc掃描controller層,mybatis掃描dao層,需要被掃描的類要增加元件註解,例如@Controller。還有一些細節問題可能會一樓記錄下來,但有事找度娘總能解決de~

到此為止,搭建Maven+Spring+SpringMVC+Mybatis的專案已經搭建完成,雖然很簡陋,出現過很多問題,但總算是成功了,可以安心睡個小覺覺 。

堅持不懈,學海無涯。