SSM框架整合Demo

目前項目大都開始採用SSM結構進行搭建,由於涉及項目比較多,新來的需求都是從現有項目中遷移一份出來進行修改,有的時候兩個項目差異仍是比較大,並不徹底須要原有項目的東西,進行刪減也是一項費神費時的事情,這裏拉一個簡單的demo,後續新的需求直接改用該項目。html

具體以下幾個步驟,搭建一個簡單的基於maven的SSM Demojava

一、建立maven項目mysql

然後按照next下一步設置相關的目錄等,搭建完的初始項目結構以下圖所示:git

二、增長java、resources等目錄github

增長test、java、resources目錄,並設置成對應的資源文件,操做以下圖:web

三、修改pom文件,引入spring、mybatis等jar文件spring

這裏根據以往項目的需求,引入了經常使用的jar,具體以下:sql

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.module</groupId>
  <artifactId>com.module</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>com.module Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
    <!-- spring版本號 -->
    <spring.version>4.3.12.RELEASE</spring.version>
    <!-- mybatis版本號 -->
    <mybatis.version>3.2.6</mybatis.version>
    <!-- log4j日誌文件管理包版本 -->
    <slf4j.version>1.7.7</slf4j.version>
    <log4j.version>1.2.17</log4j.version>
  </properties>

  <dependencies>
    <!-- 單元測試 -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <!-- 表示開發的時候引入,發佈的時候不會加載此包 -->
      <scope>test</scope>
    </dependency>
    <!-- spring核心包 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-oxm</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context-support</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <!-- mybatis核心包 -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>${mybatis.version}</version>
    </dependency>
    <!-- mybatis/spring包 -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.2.2</version>
    </dependency>
    <!-- 導入java ee jar 包 -->
    <dependency>
      <groupId>javax</groupId>
      <artifactId>javaee-api</artifactId>
      <version>7.0</version>
    </dependency>
    <!-- 導入Mysql數據庫連接jar包 -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.30</version>
    </dependency>
    <!-- 導入dbcp的jar包,用來在applicationContext.xml中配置數據庫 -->
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-dbcp2</artifactId>
      <version>2.1.1</version>
    </dependency>
    <!-- JSTL標籤類 -->
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
    <!-- 日誌文件管理包 -->
    <!-- log start -->
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>${log4j.version}</version>
    </dependency>
    <!-- 格式化對象,方便輸出日誌 -->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.2.23</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>${slf4j.version}</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>${slf4j.version}</version>
    </dependency>
    <!-- log end -->
    <!-- 映入JSON -->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.5.3</version>
    </dependency>
    <!-- 上傳組件包 -->
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.1</version>
    </dependency>
    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.4</version>
    </dependency>
    <dependency>
      <groupId>commons-codec</groupId>
      <artifactId>commons-codec</artifactId>
      <version>1.9</version>
    </dependency>

    <dependency>
      <groupId>commons-beanutils</groupId>
      <artifactId>commons-beanutils</artifactId>
      <version>1.9.3</version>
    </dependency>

    <!-- Gson json解析 -->
    <dependency>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
      <version>2.8.0</version>
    </dependency>

    <dependency>
      <groupId>org.jsoup</groupId>
      <artifactId>jsoup</artifactId>
      <version>1.10.2</version>
    </dependency>

    <!-- kaptcha圖形驗證碼 -->
    <dependency>
      <groupId>com.github.penggle</groupId>
      <artifactId>kaptcha</artifactId>
      <version>2.3.2</version>
    </dependency>

    <!-- httpclient 網絡工具 -->
    <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient</artifactId>
      <version>4.5.2</version>
    </dependency>
    <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpcore</artifactId>
      <version>4.4.5</version>
    </dependency>
    <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpmime</artifactId>
      <version>4.5.2</version>
    </dependency>
    <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient-cache</artifactId>
      <version>4.5.2</version>
    </dependency>

  </dependencies>

  <build>
    <finalName>com.module</finalName>
    <!-- 添加配置可以將sources root下的xml文件注入 -->
    <resources>
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.xml</include>
        </includes>
      </resource>
    </resources>
  </build>
</project>
View Code

四、添加日誌文件、jdbc、spring-mvc.xml及spring-mybatis.xml等文件數據庫

log4j.properties文件內容爲:apache

#日誌輸出級別,控制檯,debug文件,error文件
log4j.rootLogger = info,stdout,D,E  

#定義日誌輸出目的地爲控制檯
log4j.appender.stdout = org.apache.log4j.ConsoleAppender  
log4j.appender.stdout.Target = System.out  
#能夠靈活地指定日誌輸出格式,下面一行是指定具體的格式
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout  
log4j.appender.stdout.layout.ConversionPattern = [%c] - %m%n 

#文件大小到達指定尺寸的時候產生一個新的文件
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender  
#指定輸出目錄  到tomcat/logs下
log4j.appender.D.File = ../logs/webtest-debug.log  
#定義文件最大大小
log4j.appender.D.MaxFileSize = 10MB  
log4j.appender.D.Append = true  
log4j.appender.D.Threshold = DEBUG   
log4j.appender.D.layout = org.apache.log4j.PatternLayout  
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH\:mm\:ss}  [ %t\:%r ] - [ %p ]  %m%n  

#文件大小到達指定尺寸的時候產生一個新的文件
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender  
#指定輸出目錄  到tomcat/logs下
log4j.appender.E.File = ../logs/webtest-error.log  
#定義文件最大大小
log4j.appender.E.MaxFileSize = 10MB  
log4j.appender.E.Append = true  
log4j.appender.E.Threshold = ERROR   
log4j.appender.E.layout = org.apache.log4j.PatternLayout  
log4j.appender.E.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n


log4j.logger.org.springframework=ERROR

#顯示SQL語句部分
#log4j.logger.com.mybatis=DEBUG
#log4j.logger.com.mybatis.common.jdbc.SimpleDataSource=DEBUG
#log4j.logger.com.mybatis.common.jdbc.ScriptRunner=DEBUG
#log4j.logger.com.mybatis.sqlmap.engine.impl.SqlMapClientDelegate=DEBUG
log4j.logger.java.sql.Connection=DEBUG,stdout
log4j.logger.java.sql.Statement=DEBUG,stdout 
log4j.logger.java.sql.PreparedStatement=DEBUG,stdout
View Code

jdbc.properties文件內容爲:

driver=com.mysql.jdbc.Driver

#開發環境庫
url-test=jdbc:mysql://IP(替換成數據庫ip地址):3306/test?useUnicode=true&amp;characterEncoding=utf8&amp;autoReconnect=true
username-test=root
password-test=pass123

#定義初始鏈接數
initialSize=0
#定義最大鏈接數
maxTotal=20
#定義最大空閒
maxIdle=20
#定義最小空閒
minIdle=1
#定義最長等待時間
maxWaitMillis=60000
#空閒回收期運行週期(60秒)
timeBetweenEvictionRunsMillis=60000
View Code

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: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-3.1.xsd
                        http://www.springframework.org/schema/context
                        http://www.springframework.org/schema/context/spring-context-3.1.xsd
                        http://www.springframework.org/schema/mvc
                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

    <!-- 自動掃描該包,使SpringMVC認爲包下用了@controller註解的類是控制器 -->
    <context:component-scan base-package="com.zhouyh.controller" />
    <context:component-scan base-package="com.zhouyh.service" />

    <!--避免IE執行AJAX時,返回JSON出現下載文件 -->
    <bean id="mappingJackson2HttpMessageConverter"
          class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>text/html;charset=UTF-8</value>
            </list>
        </property>
    </bean>

    <!-- 啓動SpringMVC的註解功能,完成請求和註解POJO的映射 -->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="mappingJackson2HttpMessageConverter" />    <!-- JSON轉換器 -->
            </list>
        </property>
    </bean>

    <!-- Configures the @Controller programming model -->
    <mvc:annotation-driven />
    <!-- Handles HTTP GET requests for /resources/** by efficiently serving
        up static resources in the ${webappRoot}/resources/ directory -->
    <!-- 放置靜態文件,不作處理的,能夠直接訪問,即瀏覽器輸入地址就能夠直接訪問 -->
    <mvc:resources mapping="/resources/**" location="/resources/" />

    <!-- 定義跳轉的文件的先後綴 ,視圖模式配置 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 這裏的配置個人理解是自動給後面action的方法return的字符串加上前綴和後綴,變成一個 可用的url地址 -->
        <!-- 在webapp下有一個放置頁面的文件夾pages -->
        <property name="prefix" value="/pages/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <!-- 配置文件上傳,若是沒有使用文件上傳能夠不用配置,固然若是不配,那麼配置文件中也沒必要引入上傳組件包 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 默認編碼 -->
        <property name="defaultEncoding" value="utf-8" />
        <!-- 文件大小最大值 -->
        <property name="maxUploadSize" value="10485760000" />
        <!-- 內存中的最大值,寫大時小文件不會生產臨時文件,影響同步 -->
        <property name="maxInMemorySize" value="1" />
    </bean>

    <!-- 配置kaptcha驗證碼 -->
    <bean id="captchaProducer" class="com.google.code.kaptcha.impl.DefaultKaptcha">
        <property name="config">
            <bean class="com.google.code.kaptcha.util.Config">
                <constructor-arg type="java.util.Properties">
                    <props>
                        <!-- 圖片無邊框 -->
                        <prop key="kaptcha.border">no</prop>
                        <!-- 圖片寬度 -->
                        <prop key="kaptcha.image.width">100</prop>
                        <!-- 圖片高度 -->
                        <prop key="kaptcha.image.height">42</prop>
                        <!-- 噪點實現類 -->
                        <prop key="kaptcha.noise.impl">com.google.code.kaptcha.impl.NoNoise</prop>
                        <!-- 圖片樣式 -->
                        <prop key="kaptcha.obscurificator.impl">com.boryou.yuqing.util.CaptchaRender</prop>
                        <!-- 背景顏色漸變,開始顏色 -->
                        <prop key="kaptcha.background.clear.from">215,235,241</prop>
                        <!-- 背景顏色漸變,結束顏色 -->
                        <prop key="kaptcha.background.clear.to">215,235,241</prop>
                        <!-- 驗證碼文字取值範圍 -->
                        <prop key="kaptcha.textproducer.char.string">0123456789</prop>
                        <!-- 驗證碼長度 -->
                        <prop key="kaptcha.textproducer.char.length">5</prop>
                        <!-- 驗證碼文字顏色 -->
                        <prop key="kaptcha.textproducer.font.color">0,161,233</prop>
                        <!-- 驗證碼文字大小 -->
                        <prop key="kaptcha.textproducer.font.size">30</prop>
                    </props>
                </constructor-arg>
            </bean>
        </property>
    </bean>
</beans>
View Code

spring-mybatis.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: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-3.1.xsd    
                        http://www.springframework.org/schema/context    
                        http://www.springframework.org/schema/context/spring-context-3.1.xsd    
                        http://www.springframework.org/schema/mvc    
                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
    
    <!-- 引入配置文件 -->
    <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:jdbc.properties" />
    </bean>

    <!-- 本系統數據庫配置 -->
    <bean id="dataSource-base" class="org.apache.commons.dbcp2.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName" value="${driver}" />
        <!-- 初始化鏈接大小 -->
        <property name="initialSize" value="${initialSize}"/>
        <!-- 鏈接池最大數量 -->
        <property name="maxTotal" value="${maxTotal}"/>
        <!-- 鏈接池最大空閒 -->
        <property name="maxIdle" value="${maxIdle}"/>
        <!-- 鏈接池最小空閒 -->
        <property name="minIdle" value="${minIdle}"/>
        <!-- 獲取鏈接最大等待時間 -->
        <property name="maxWaitMillis" value="${maxWaitMillis}"/>
        <!-- 指明鏈接是否被空閒鏈接回收器(若是有)進行檢驗 -->
        <property name="testWhileIdle" value="true"/>
        <!-- 運行一次空閒鏈接回收器的時間間隔(60秒)-->
        <property name="timeBetweenEvictionRunsMillis" value="${timeBetweenEvictionRunsMillis}"/>
        <!-- 驗證時使用的SQL語句 -->
        <property name="validationQuery" value="SELECT 1" />
        <!-- 借出鏈接時不要測試,不然很影響性能 -->
        <property name="testOnBorrow" value="false"/>
    </bean>
    <!-- 開發環境庫 -->
    <bean id="dataSource-test" parent="dataSource-base">
        <property name="url" value="${url-test}" />
        <property name="username" value="${username-test}" />
        <property name="password" value="${password-test}" />
    </bean>


    <!-- spring和MyBatis完美整合,不須要mybatis的配置映射文件 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource-test" />
        <property name="configLocation" value="classpath:sqlMapConfig.xml"></property>
        <!-- 自動掃描mapping.xml文件 -->
        <property name="mapperLocations" value="classpath:com/zhouyh/mapper/*.xml"></property>
    </bean>

    <!-- DAO接口所在包名,Spring會自動查找其下的類 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.zhouyh.dao" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
    </bean>

    <!-- (事務管理)transaction manager, use JtaTransactionManager for global tx -->
    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource-test" />
    </bean>


</beans>
View Code

五、根據須要添加controller、dao、mapper、service等文件,整合web.xml文件

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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0">
  <display-name>Archetype Created Web Application</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>

  <!-- web.xml配置 -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring-mybatis.xml</param-value>
  </context-param>
  <servlet>
    <servlet-name>SpringMVC</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>
    <load-on-startup>1</load-on-startup>
    <async-supported>true</async-supported>
  </servlet>
  <servlet-mapping>
    <servlet-name>SpringMVC</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <listener>
    <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
  </listener>

</web-app>
View Code

六、最後完成項目總體結構如圖所示:

至此,簡單的Demo已經完成。

 代碼上傳到了GitHub上,連接爲:MavenWebDemo

相關文章
相關標籤/搜索