ssm框架的整合(spring+ springMVC+MyBatis)

SSM框架整合

1.搭建環境

1.1 創建數據表

  • 使用的是MySQL數據庫,創建數據庫名爲ssm,再創建一張名爲account的表。
CREATE DATABASE ssm;
USE ssm;
CREATE TABLE account(
id INT PRIMARY KEY auto_increment,
NAME VARCHAR(20),
money DOUBLE
);

1.2 創建項目

  • 本項目使用的是編寫工具爲IDEA,基於maven的WEB項目,首先新建項目new Project,如下圖;

    [外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-SP4JsZQt-1579081351866)(C:\Users\yulu\Desktop\臨時\img_1.png)]

    然後選擇Next,界面如下,填寫項目有關信息;

    [外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-hN4kd2I9-1579081351867)(C:\Users\yulu\Desktop\臨時\img_2.jpg)]

然後選擇Next,界面如下,選擇對應的maven版本;

[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-n0TSHUre-1579081351867)(C:\Users\yulu\Desktop\臨時\img_3.png)]

然後選擇Next,界面如下,選擇項目創建的路徑;

[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-Rc9dfeJX-1579081351867)(C:\Users\yulu\Desktop\臨時\img_4.png)]

然後選擇Finish,此時,項目就算構建完成了,控制檯會提示[INFO] BUILD SUCCESS。

1.3 引入相關的maven座標。

  • 由於需要引入的座標比較多這裏沒有列舉。

1.4 創建包,以及編寫基本代碼。

  • 具體項目基本目錄結構如下圖。

    [外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-R1fVs2i9-1579081351868)(C:\Users\yulu\Desktop\臨時\img_5.png)]

2. 搭建Spring框架並測試。

2.1 applicationContext.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:context="http://www.springframework.org/schema/context"
       xmlns:spring="http://www.springframework.org/schema/tool"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx
        https://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/tool http://www.springframework.org/schema/tool/spring-tool.xsd">

    <!--開啓註解的掃描 ,只處理service和dao-->
    <context:component-scan base-package="cn.****">
        <!--配置哪些註解不掃描-->
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

</beans>

2.2 Log4j的配置文件log4j.properties.

# Set root category priority to INFO and its only appender to CONSOLE.
#log4j.rootCategory=INFO, CONSOLE            debug   info   warn error fatal
log4j.rootCategory=info, CONSOLE, LOGFILE

# Set the enterprise logger category to FATAL and its only appender to CONSOLE.
log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE

# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n

# LOGFILE is set to be a File appender using a PatternLayout.
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=d:\axis.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n

2.3測試spring框架是否可以使用

  • 編寫一個測試類,將我們的AccountService交給spring容器爲我們創建,測試是否正常。

    package cn.****.test;
    
    import cn.****.service.AccountService;
    import org.junit.Test;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    public class TestSpring {
    
        @Test
        public void run1(){
            //加載spring的配置文件
            ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
            //獲取對象
            AccountService as = (AccountService) ac.getBean("accountService");
            //調用方法
            as.findAll();
        }
    }
    
    

3. 搭建SpringMVC框架,並測試

3.1編寫web.xml

  • 配置前端控制器和解決中文亂碼。

    <!DOCTYPE web-app PUBLIC
     "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
     "http://java.sun.com/dtd/web-app_2_3.dtd" >
    
    <web-app>
      <display-name>Archetype Created Web Application</display-name>
      
      <!--配置前端控制器-->
      <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--加載springmvc.xml的配置文件-->
        <!--啓動服務器就創建該servlet-->
        <init-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>classpath:springmvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
      </servlet>
      <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
      </servlet-mapping>
      
      <!--解決中文亂碼的過濾器-->
      <filter>
        <filter-name>characterEncodingFilter</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>characterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
      </filter-mapping>
    </web-app>
    
    

3.2 編寫springmvc.xml

  • 配置springmvc註解要掃描的包,視圖解析器,配置需要過濾的靜態資源,開啓springMVC的註解支持。

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:mvc="http://www.springframework.org/schema/mvc"
           xmlns:context="http://www.springframework.org/schema/context"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="
            http://www.springframework.org/schema/beans
            https://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/mvc
            https://www.springframework.org/schema/mvc/spring-mvc.xsd
            http://www.springframework.org/schema/context
            https://www.springframework.org/schema/context/spring-context.xsd">
    
        <!--開啓註解掃描-->
        <context:component-scan base-package="cn.****">
            <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
        </context:component-scan>
    
        <!--配置視圖解析器對象-->
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
            <property name="prefix" value="/WEB-INF/pages/"></property>
            <property name="suffix" value=".jsp"></property>
        </bean>
    
        <!--過濾靜態的資源-->
        <mvc:resources mapping="/css/**" location="/css/"></mvc:resources>
        <mvc:resources mapping="/images/**" location="/images/"></mvc:resources>
        <mvc:resources mapping="/js/**" location="/js/"></mvc:resources>
    
        <!--開啓springMVC的註解支持-->
        <mvc:annotation-driven />
    
    </beans>
    

3.3 測試

  • 在index.jsp中寫一個超鏈接。

    <%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="utf-8" %>
    <html>
    <head>
        <title>index</title>
    </head>
    <body>
    <h3>index</h3>
    <a href="account/findAll">測試</a>
    </body>
    </html>
    
  • 編寫AccountController.java,最後啓動服務器看是否能夠執行成功。

    package cn.****.controller;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    /**
    
    - 賬戶WEB
      */
      @Controller
      @RequestMapping("/account")
      public class AccountController {
    
      @RequestMapping("/findAll")
      public String findAll(){
          System.out.println("表現層,查詢所有的信息。。。");
          return "list";
      }
      }
    

4.Spring框架整合SpringMVC

4.1 配置當服務器啓動時同時也需要加載spring的配置文件,所以需要在web.xml文件里加上配置。

<!--配置spring的監聽器,默認只加載WEB/INF目錄下的applicationContext.xml配置文件-->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <!--設置配置文件的路徑-->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
  • 此時,controller就可以通過依賴注入的方式創建service對象,並調用。

5. 搭建Mybatis框架,並測試。

5.1 編寫數據庫的基本配置文件SqlMapConfig.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>
    <!--配置環境-->
    <environments default="mysql">
        <environment id="mysql">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/ssm"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    <!--引入的應色配置文件-->
    <mappers>
<!--        <mapper resource="cn/****/dao/xxx.xml"></mapper>-->
<!--        <mapper class="cn.****.dao.AccountDao"></mapper>-->
<!--        <mapper class="cn.****.dao.UserDao"></mapper>-->
        <package name="cn.****.dao"/>
    </mappers>

</configuration>

5.2 編寫sql語句,可以採用註解的方式,也可以採用映射文件的方式。

  • 採用註解的方式,只需在dao接口裏的方法上面編寫sql語句,例如:

    //查詢所有賬戶信息
    @Select("select * from account")
    public List<Account> findAll();
    

5.3 編寫測試方法

@Test
public void run1() throws IOException {
    //加載mybatis的配置文件
    InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
    //創建SqlSessionFactory對象
    SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
    //創建SqlSeeion對象
    SqlSession seession = factory.openSession();
    //獲取代理對象
    AccountDao dao = seession.getMapper(AccountDao.class);
    //查詢所有的數據
    List<Account> list = dao.findAll();
    for (Account account : list) {
        System.out.println(account);
    }
    //關閉資源
    seession.close();
    in.close();
}

6. Spring框架整合Mybatis框架

6.1 將Mybatis的相關的配置文件轉移到Spring的配置文件中。

  • 將配置連接池,配置SqlSessionFactory工廠,配置接口所在的包,以及Spring框架聲明式事務管理等。

    <!--spring整合Mybatis框架-->
        <!--配置連接池-->
        <bean class="com.mchange.v2.c3p0.ComboPooledDataSource" id="dataSource">
            <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
            <property name="jdbcUrl" value="jdbc:mysql://localhost/ssm"></property>
            <property name="user" value="root"></property>
            <property name="password" value="root"></property>
        </bean>
        <!--配置SqlSeeionFactory工廠-->
        <bean class="org.mybatis.spring.SqlSessionFactoryBean" id="sqlSessionFactory">
            <property name="dataSource" ref="dataSource"></property>
        </bean>
        <!--配置接口所在的包-->
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" id="mapperScannerConfigurer">
            <property name="basePackage" value="cn.***.dao"></property>
        </bean>
    
        <!--配置Spring框架聲明式事務管理-->
        <!--配置事務管理器-->
        <bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager" id="transactionManager">
            <property name="dataSource" ref="dataSource"></property>
        </bean>
        <!--配置事務的通知-->
        <tx:advice id="txAdvice" transaction-manager="transactionManager">
            <tx:attributes>
                <tx:method name="find*" read-only="true"/>
                <tx:method name="*" isolation="DEFAULT"/>
            </tx:attributes>
        </tx:advice>
        <!--配置AOP增強-->
        <aop:config>
            <aop:advisor advice-ref="txAdvice" pointcut="execution(* cn.****.service.impl.*ServiceImpl.*(..))"/>
        </aop:config>
    
發佈了11 篇原創文章 · 獲贊 7 · 訪問量 1732
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章