手刃SSM(Spring+SpringMVC+Mybatis)--第一彈

@(關(guān)鍵字)[Spring|SpringMVC|Mybatis]


主要框架簡介

Spring:Spring官方文檔;
SpringMVC:SpringMVC官方文檔;
Mybatis:Mybatis官方文檔.

動手干起來

一、eclipse中新建Maven項(xiàng)目

  1. 如下圖,選擇Catalogs中的maven-archetype-webapp;

為什么選擇maven-archetype-webapp?
我們需要建的是web工程,所以直接使用這個(gè)創(chuàng)建于web項(xiàng)目相關(guān)的文件夾和項(xiàng)目目錄結(jié)構(gòu),就是這樣子

1_New project_maven.png

  1. 之后Next,輸入Group Id和Artifact Id就可以點(diǎn)擊Ok了。

Group Id:項(xiàng)目的全球唯一標(biāo)識符,通常使用全限定的包名區(qū)分該項(xiàng)目和其他項(xiàng)目。并且構(gòu)建時(shí)生成的路徑也是由此生成, 如com.company.app生成的相對路徑為:/com/company/app
Artifact Id:構(gòu)件的標(biāo)識符,它和group ID一起唯一標(biāo)識一個(gè)構(gòu)件。

  1. 等待maven自動構(gòu)建項(xiàng)目結(jié)構(gòu),在完成之后,可能會出現(xiàn)以下情況:
  1. 錯(cuò)誤:在index.jsp文件中報(bào)錯(cuò):The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path
    解決方案:在項(xiàng)目名上點(diǎn)擊右鍵,找到build path->library->add library->Server Runtime->選擇你的服務(wù)器(tomcat 7/8);
  1. 在完成以上步驟之后,將必要的源碼包補(bǔ)全,項(xiàng)目結(jié)構(gòu)如下圖:


    5_project_struct.png

二、開始寫代碼

  1. 根據(jù)spring+springMVC+mybatis+Mysql+log4j框架,決定我們此項(xiàng)目所需要哪些依賴。關(guān)鍵幾個(gè)框架所用到的版本號如下:
<properties> 
  <maven.compiler.target>1.8</maven.compiler.target
  <maven.compiler.source>1.8</maven.compiler.source
  <mysql.version>5.1.38</mysql.version
  <druid.version>1.0.18</druid.version
  <servlet.version>3.1.0</servlet.version
  <jedis.version>2.7.3</jedis.version
  <protostuff.version>1.0.8</protostuff.version
  <spring.version>4.0.2.RELEASE</spring.version
  <mybatis.version>3.2.6</mybatis.version
  <slf4j.version>1.7.7</slf4j.version> <log4j.version>1.2.17</log4j.version
</properties>
  1. 配置web.xml文件,所有配置將添寫注釋

在web.xml文件中,主要配置servlet及其映射關(guān)系、監(jiān)聽器和過濾器。具體可參考源碼

<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    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>
    
    <!-- Log4j配置文件 -->
    <context-param>
        <param-name>log4jConfigLocation</param-name>
        <param-value>classpath:log4j.xml</param-value>
    </context-param>
    <context-param>
        <param-name>log4jRefreshInterval</param-name>
        <param-value>60000</param-value>
    </context-param>
    <listener>
        <listener-class>
            org.springframework.web.util.Log4jConfigListener
        </listener-class>
    </listener>
    
    <servlet>
        <display-name>SpringRain</display-name> <!-- 項(xiàng)目名稱 -->
        <servlet-name>SpringMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- 配置springMVC需要加載的配置文件 spring-dao.xml,spring-service.xml,spring-web.xml 
            Mybatis - > spring -> springmvc -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring/spring-*.xml</param-value>
        </init-param>
        
         <load-on-startup>1</load-on-startup>  <!-- 容器加載該Servlet的優(yōu)先級 -->
        <async-supported>true</async-supported><!-- 啟動異步支持 -->
    </servlet>
    <servlet-mapping>
        <servlet-name>SpringMVC</servlet-name>
        <!-- 默認(rèn)匹配所有的請求 -->
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!--druid WEB方式監(jiān)控配置 -->
    <servlet>
        <servlet-name>DruidStatView</servlet-name>
        <servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>DruidStatView</servlet-name>
        <url-pattern>/druid/*</url-pattern>
    </servlet-mapping>
    <filter>
        <filter-name>druidWebStatFilter</filter-name>
        <filter-class>com.alibaba.druid.support.http.WebStatFilter</filter-class>
        <init-param>
            <param-name>exclusions</param-name>
            <param-value>/public/*,*.js,*.css,/druid*,*.jsp,*.swf</param-value>
        </init-param>
        <init-param>
            <param-name>principalSessionName</param-name>
            <param-value>sessionInfo</param-value>
        </init-param>
        <init-param>
            <param-name>profileEnable</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>druidWebStatFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    
    <!-- 編碼過濾器 -->
    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter
        </filter-class>
        <async-supported>true</async-supported>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    
    <!-- 默認(rèn)頁面 -->
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    <!-- 錯(cuò)誤頁面的處理 -->
    <error-page>
        <exception-type>java.lang.NullPointerException</exception-type>
        <location>/WEB-INF/common/error.html</location>
    </error-page>
    <error-page>
        <exception-type>java.lang.NumberFormatException</exception-type>
        <location>/WEB-INF/common/error.html</location>
    </error-page>
    <error-page>
        <error-code>404</error-code>
        <location>/WEB-INF/common/404.html</location>
    </error-page>
    <error-page>
        <error-code>500</error-code>
        <location>/WEB-INF/common/500.html</location>
    </error-page>
    
</web-app>

3.配置spring-mybatis.xml文件

該文件主要整合spring與mybatis;

<?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">

    <!-- 本文件整合Spring與Mybatis -->
    <!-- 使用數(shù)據(jù)庫配置文件,可以使得配置解耦 -->
    <context:property-placeholder location="classpath:jdbc.properties"/>
    
    <!-- Druid配置 -->
    <!-- 數(shù)據(jù)庫連接池相關(guān) -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
            init-method="init" destroy-method="close">
          <!-- 配置連接池屬性 -->
          <property name="driverClassName" value="${jdbc.driver}"/>
          <property name="url" value="${jdbc.url}"/>
          <property name="username" value="${jdbc.username}"/>
          <property name="password" value="${jdbc.password}"/>

          <!-- 配置初始化大小、最小、最大 -->
          <property name="initialSize" value="${initialSize}" />
          <property name="maxIdle" value="${maxIdle}" />
          <property name="minIdle" value="${minIdle}" />
          <property name="maxActive" value="${maxActive}" />

          <!-- 配置獲取連接等待超時(shí)的時(shí)間 -->
          <property name="maxWait" value="10000" />

          <!-- 配置間隔多久才進(jìn)行一次檢測,檢測需要關(guān)閉的空閑連接,單位是毫秒 -->
          <property name="timeBetweenEvictionRunsMillis" value="60000" />

          <!-- 配置一個(gè)連接在池中最小生存的時(shí)間,單位是毫秒 -->
          <property name="minEvictableIdleTimeMillis" value="300000" />

          <property name="testWhileIdle" value="true" />

          <!-- 這里建議配置為TRUE,防止取到的連接不可用 -->
          <property name="testOnBorrow" value="true" />
          <property name="testOnReturn" value="false" />

          <!-- 打開PSCache,并且指定每個(gè)連接上PSCache的大小 -->
          <property name="poolPreparedStatements" value="true" />
          <property name="maxPoolPreparedStatementPerConnectionSize"
                    value="20" />

          <!-- 這里配置提交方式,默認(rèn)就是TRUE,可以不用配置 -->

          <property name="defaultAutoCommit" value="true" />

          <!-- 驗(yàn)證連接有效與否的SQL,不同的數(shù)據(jù)配置不同 -->
          <property name="validationQuery" value="select 1 " />
          <property name="filters" value="stat" />
          <property name="proxyFilters">
              <list>
                  <ref bean="logFilter" />
              </list>
          </property>
      </bean>
      
      <bean id="logFilter" class="com.alibaba.druid.filter.logging.Slf4jLogFilter">
          <property name="statementExecutableSqlLogEnable" value="false" />
      </bean>
      
      <!-- 配置SqlSessionFactory對象 -->
      <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
          <!-- 注入數(shù)據(jù)庫連接池 -->
          <property name="dataSource" ref="dataSource"/>
          <!-- 配置Mybatis全局配置文件:mybatis-config.xml -->
          <property name="configLocation" value="classpath:mybatis-config.xml"/>
          <!-- 掃描entity包 使用別名 -->
          <!-- 即項(xiàng)目的GroupId -->
          <property name="typeAliasesPackage" value="com.person.entity"/>
          <!-- 掃描sql配置文件:mapper需要的xml文件 -->
          <property name="mapperLocations" value="classpath:mapper/*.xml"/>
      </bean>
      
      <!-- 配置掃描Dao接口包,動態(tài)實(shí)現(xiàn)Dao接口,注入到spring容器中 -->
      <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
          <!-- 注入sqlSessionFactory -->
          <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
          <!-- 給出需要掃描Dao接口包 -->
          <property name="basePackage" value="com.person.dao"/>
      </bean>
      
      <!-- none -->
      <!-- 事務(wù)管理配置 -->
    <!-- <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean> -->
    
    <!-- AOP切面 -->
    <!-- <aop:aspectj-autoproxy /> -->
    <!-- 自動裝載aop -->
    <!-- <bean id="logAspect" class="com.person.aop.LogAspect" /> --><!-- 切面定義(采用注解的方式定義及使用) -->
    
      
</beans>

4.配置spring-service.xml文件

該文件主要配合事務(wù)處理相關(guān)的bean;

<?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:tx="http://www.springframework.org/schema/tx"
         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/tx
      http://www.springframework.org/schema/tx/spring-tx.xsd">

      <!-- 掃描service包下所有使用注解的類型 -->
      <!-- package值為"GroupId+存放services的包名 -->
      <context:component-scan base-package="com.person.service" />

      <!-- 配置事務(wù)管理器 -->
      <bean id="transactionManager"
            class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
          <!-- 注入數(shù)據(jù)庫連接池 -->
          <property name="dataSource" ref="dataSource" />
      </bean>

      <!-- 配置基于注解的聲明式事務(wù) -->
      <tx:annotation-driven transaction-manager="transactionManager" />
  </beans>

5.配置spring-web.xml文件

該文件主要處理視圖、控制器部分的內(nèi)容

<?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-3.0.xsd">
    <!-- 配置SpringMVC -->
    <!-- 開啟SpringMVC注解模式 -->
    <mvc:annotation-driven/>
    <!-- 靜態(tài)資源默認(rèn)servlet配置 -->
     <mvc:resources location="/static/common/" mapping="/common/**"/>
    <mvc:resources  location="/static/css/" mapping="/css/**"/>
    <mvc:resources  location="/static/images/" mapping="/images/**" />
    <mvc:resources  location="/static/view/" mapping="/view/**" />
    <mvc:default-servlet-handler/>

    <!-- 配置jsp 顯示ViewResolver -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <property name="prefix" value="/WEB-INF/view/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <!-- 掃描web相關(guān)的bean -->
    <context:component-scan base-package="com.person.controller">
        <!-- 制定掃包規(guī)則 ,只掃描使用@Controller注解的JAVA類 -->
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

</beans>

6.在經(jīng)過以上步驟,基本上已完成了框架的整合,但是在配置過程中,我們在配置文件中又引入了jdbc.properties、log4j.xml、mybatis-config.xml三個(gè)文件,故我們需要在src/main/resources目錄中新建并配置這幾個(gè)文件。具體代碼參考github項(xiàng)目

7.將項(xiàng)目部署到tomcat中,在瀏覽器總訪問http:localhost:8080/SpringRain,將會訪問到index.jsp頁面

8.配置結(jié)束

9.上傳github

有關(guān)上傳項(xiàng)目到github的教程請參考我的另一篇文章-->"從零開始Git"。

反饋與建議


非常感謝您閱讀這份幫助文檔。點(diǎn)擊分享按鈕,分享給更多的人唄。


wechat.jpg

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容