1. 程式人生 > 其它 >java整合SSM的基本配置

java整合SSM的基本配置

如果只實現簡單的CRUD用到的技術有以下幾點,那麼我們就基於以下幾點做一個配置
基礎框架 ssm(Spring-SpringMVC-Mybatis)

資料庫 Mysql

前端框架 bootStrap

專案管理工具 maven

逆向工程-Mybatis-Generator 自動生成程式碼

首先配置Spring的配置檔案

**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:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:util="http://www.springframework.org/schema/util"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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/util http://www.springframework.org/schema/util/spring-util.xsd
         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
         http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
         http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
">
        
        <!--掃描業務元件-->
        <context:component-scan base-package="com.wanghao.ssm">
                <!--除了控制器,其他的業務邏輯元件都要掃-->
                <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
        </context:component-scan>
        
        <!--Spring的配置檔案,這裡主要配置和業務邏輯有關的資訊-->
        <!--資料來源,事務控制-->
        <context:property-placeholder location="dbconfig.properties"></context:property-placeholder>
        <bean id="pooledDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
                <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
                <property name="driverClass" value="${jdbc.driverClass}"></property>
                <property name="user" value="${jdbc.user}"></property>
                <property name="password" value="${jdbc.password}"></property>
        </bean>

        <!--配置和mybatis的整合,建立SqlSessionFactory物件-->
        <bean id="SqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
                <!--指定mybatis全域性配置檔案的位置-->
                <property name="configLocation" value="classpath:mybatis-config.xml"></property>
                <!--指定資料來源-->
                <property name="dataSource" ref="pooledDataSource"></property>
                <!--指定mybatis mapper檔案的位置-->
                <property name="mapperLocations" value="classpath:mapper/*.xml"></property>
        </bean>

        <!--配置掃描器,將Mybatis介面的實現加入到IOC容器中-->
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
                <property name="basePackage" value="com.wanghao.ssm"></property>
        </bean>

        <!--事務控制-->
        <bean id="DataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
                <!--控制住資料來源-->
                <property name="dataSource" ref="pooledDataSource"></property>
        </bean>

        <!--開啟基於註解的事務,或使用xml配置的事務(主要的都是使用配置式)-->
        <aop:config>
                <!--切入點表示式-->
                <aop:pointcut id="txpoint" expression="execution(* com.wanghao.ssm..*(..))"></aop:pointcut>
                <!--配置事務增強-->
                <aop:advisor advice-ref="txadvice" pointcut-ref="txpoint"/>
        </aop:config>

        <!--配置事務增強,事務如何切入-->
        <tx:advice id="txadvice" transaction-manager="DataSourceTransactionManager">
                <tx:attributes>
                        <!--所有方法都是事務方法-->
                        <tx:method name="*"/>
                        <tx:method name="get*" read-only="true"/>
                        <!-- 為什麼要設定  read-only true 當事務方法為get*開頭的方法時,我們預設其執行的是查詢操作
                         如果你一次執行單條查詢語句,則沒有必要啟用事務支援,資料庫預設支援SQL執行期間的讀一致性;
如果你一次執行多條查詢語句,例如統計查詢,報表查詢,在這種場景下,多條查詢SQL必須保證整體的讀一致性,
否則,在前條SQL查詢之後,後條SQL查詢之前,資料被其他使用者改變,則該次整體的統計查詢將會出現讀資料不一致的狀態,此時,應該啟用事務支援。
【注意是一次執行多次查詢來統計某些資訊,這時為了保證資料整體的一致性,要用只讀事務】
                        -->
                </tx:attributes>
        </tx:advice>

        <!--Spring配置檔案按的核心點:(資料來源、與mybatis整合、事務控制)-->
</beans>

資料庫的配置

 dbconfig.properties
  jdbc.jdbcUrl=jdbc:mysql://localhost:3306/ssm_crud?&useSSL=false&serverTimezone=UTC
  jdbc.driverClass=com.mysql.cj.jdbc.Driver
  jdbc.user=root
  jdbc.password=xxxx

SpringMVC的配置

<?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"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       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 http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
        <!--SpringMVC的配置檔案,包含網站跳轉邏輯的控制 配置-->
            <!--掃描所有的業務邏輯元件-->
    <context:component-scan base-package="com.wanghao.ssm" use-default-filters="false">
        <!--SpringMVC不能掃描所有的元件註解,所有我們設定只掃描控制器-->
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"></context:include-filter>
    </context:component-scan>

    <!--配置檢視解析器,方便頁面返回 檢視渲染-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

    <!--兩個標準配置-->
    <!--1.預設的servlet處理器,將Springmvc不能處理的請求交給tomcat,這樣就使得動靜態資源都能訪問了-->
    <mvc:default-servlet-handler/>
    <!--2.註解驅動,可以支援SpringMVC更高階一些的功能,比如JSR303校驗,快捷的ajax請求...對映動態請求,檢視處理器-->

    <mvc:annotation-driven/>
</beans>

web下的配置

web.xml
  <?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <!--啟動Spring容器-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>

    <!--配置Springmvc的前端控制器,攔截所有請求-->
    <servlet>
        <servlet-name>DispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <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</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>
        <init-param>
            <param-name>forceRequestEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
        <init-param>
            <param-name>forceResponseEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    
    <!--使用Restful風格的URI,配置隱式過濾器-->
    <filter>
        <filter-name>HiddenHttpMethodFilter</filter-name>
        <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
    </filter>
   <filter-mapping>
       <filter-name>HiddenHttpMethodFilter</filter-name>
       <url-pattern>/*</url-pattern>
   </filter-mapping>
</web-app>

以上基本就是整合SSM的全部配置內容,但由於考慮要寫的mapper,pojo 等程式碼量太大,我們可以使用mybatis的逆向工程,來自動生成我們所需要的程式碼
在工程下建立mbg.xml進行以下配置:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
    <context id="DB2Tables" targetRuntime="MyBatis3">
        <commentGenerator>
            <!-- 是否去除自動生成的註釋 -->
            <property name="suppressAllComments" value="true" />
        </commentGenerator>
        <!-- Mysql資料庫連線的資訊:驅動類、連線地址、使用者名稱、密碼 -->
        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/ssm_crud?useUnicode=true&amp;characterEncoding=utf-8&amp;
                        useSSL=false&amp;serverTimezone = GMT"
                        userId="root"
                        password="xxxx"
        />
        <!-- 預設為false,把JDBC DECIMAL 和NUMERIC型別解析為Integer,為true時 把JDBC DECIMAL 和NUMERIC型別解析為java.math.BigDecimal -->
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>
        <!-- targetProject:生成POJO類的位置 -->
        <javaModelGenerator
                targetPackage="com.wanghao.ssm.Entity" targetProject=".\src\main\java">
            <!-- enableSubPackages:是否讓schema作為包的字尾 -->
            <property name="enableSubPackages" value="true" />
            <!-- 從資料庫返回的值被清理前後的空格 -->
            <property name="trimStrings" value="true" />
        </javaModelGenerator>
        <!-- targetProject:mapper對映檔案生成的位置 -->
        <sqlMapGenerator targetPackage="mapper"
                         targetProject=".\src\main\resources">
            <!-- enableSubPackages:是否讓schema作為包的字尾 -->
            <property name="enableSubPackages" value="false" />
        </sqlMapGenerator>
        <!-- targetProject:mapper介面生成的的位置 -->
        <javaClientGenerator type="XMLMAPPER"
                             targetPackage="com.wanghao.ssm.Dao" targetProject=".\src\main\java">
            <!-- enableSubPackages:是否讓schema作為包的字尾 -->
            <property name="enableSubPackages" value="true" />
        </javaClientGenerator>
        <!-- 指定資料表 -->
        <table tableName="emp" domainObjectName="Employee"></table>
        <table tableName="dept" domainObjectName="Department"></table>
    </context>
</generatorConfiguration>

進行程式碼生成測試

  @Test
    public void generator() throws Exception {
        List<String> warnings = new ArrayList<String> ();
        boolean overwrite = true;
        // 指定配置檔案
        File configFile = new File ("mbg.xml");
        ConfigurationParser cp = new ConfigurationParser (warnings);
        Configuration config = cp.parseConfiguration(configFile);
        DefaultShellCallback callback = new DefaultShellCallback(overwrite);
        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
        myBatisGenerator.generate(null);
    }