1. 程式人生 > >ssm專案整合步驟

ssm專案整合步驟

第一步:整合dao層
mybatis 和 spring ,通過 spring 管理 mapper 介面。
使用 mapper 的掃描器自動掃描 mapper 介面 在spring中進行註冊。

MConfig.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
>
<!--全域性setting配置,根據需要新增--> <settings> <!-- <setting name="logImpl" value="LOG4J"/>--> <setting name="logImpl" value="LOG4J"/> <!--設定延遲載入--> <!--<setting name="lazyLoadingEnabled" value="true"/>--> <!--<setting name="aggressiveLazyLoading" value="false"/>-->
<!--設定二級快取--> <setting name="cacheEnabled" value="true"/> </settings> <!--配置別名 --> <typeAliases> <!--批量掃描--> <package name="com.demo.ssm.po"/> </typeAliases> <!--載入對映檔案--> <mappers> <!--<mapper resource="sqlmap/user.xml"/>-->
<!--載入單個對映檔案 resource從類路徑開 url跟路徑--> <!--spring 整合後,使用mapper掃描器,不需要配置--> <!-- <mapper resource="mapper/User.xml"/> --> <package name="com.demo.ssm.mapper"/> </mappers> </configuration>

applicationContext-dao.xml

配置資料來源
配置sqlSessionFactory
配置mapper掃描器

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

    <!--載入配置檔案-->
    <context:property-placeholder location="db.properties"/>


    <!--配置資料來源-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <!-- 指定連線資料庫的驅動-->
        <property name="driverClass" value="${jdbc.driver}"/>
        <!-- 指定連線資料庫的URL-->
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <!-- 指定連線資料庫的使用者名稱-->
        <property name="user" value="${jdbc.username}"/>
        <!-- 指定連線資料庫的密碼-->
        <property name="password" value="${jdbc.password}"/>
    </bean>

<!--配置sqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--載入mybatis的配置檔案-->
        <property name="configLocation" value="mybatis/MConfig.xml" />
        <property name="dataSource" ref="dataSource"/>
    </bean>


    <!--mapper 配置
        根據mapper介面生產mapper物件
    -->
    <!--此方法需要針對每一個mapper配置,麻煩。-->
    <!--<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">-->
        <!--&lt;!&ndash;mapperInterface 指定mapper介面&ndash;&gt;-->
        <!--<property name="mapperInterface" value="com.demo.mybatis.mapper.UserMapper"/>-->
        <!--<property name="sqlSessionFactory" ref="sqlSessionFactory"/>-->
    <!--</bean>-->

    <!--mapper批量掃描,從mapper包中掃描出mapper介面,自動建立代理物件並且在spring容器中註冊-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--指定掃描的包名-->
        <!--使用掃描需要遵循一下規範:
            mapper.xml與mapper.java檔名稱一致,並在同個目錄下
        -->
        <!--自動掃描出來的mapper的bean的id為mapper的類名(首字母小寫)-->
        <!--如果要掃描多個包,用半形逗號分隔包名-->
        <property name="basePackage" value="com.demo.ssm.mapper"/>

        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    </bean>
</beans>

逆向工程生產po類mapper(單表CRUD)
mybatis-generator.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="testDb">
        <!--資料庫連線的資訊:驅動類,連線地址,使用者名稱,密碼-->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/mdb" userId="root" password="root"></jdbcConnection>
<!--
        <jdbcConnection driverClass="oracle" connectionURL="jdbc:oracle:thin:@127.0.0.1:1521:mdb" userId="root" password="root"></jdbcConnection>
-->
        <!--生成po類的位置-->
        <javaModelGenerator targetPackage="com.demo.ssm.po" targetProject=".\src\main\java"></javaModelGenerator>


        <!--mapper檔案位置-->
        <sqlMapGenerator targetPackage="com.demo.ssm.mapper" targetProject=".\src\main\java"></sqlMapGenerator>

        <!--mapper介面位置-->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.demo.ssm.mapper" targetProject=".\src\main\java"></javaClientGenerator>


        <!--指定資料庫表-->
        <table tableName="item"></table>
        <table tableName="user"></table>
        <table tableName="orderdetail"></table>
        <table tableName="orders"></table>

    </context>
</generatorConfiguration>        

Generator.java

public class Generator {
    public void generator() throws IOException, XMLParserException, InvalidConfigurationException, SQLException, InterruptedException {
        List<String> warnings = new ArrayList<String>();
        boolean overwrite = true;
        File configFile = new File("src/main/resources/generator/generatorConfig.xml");
        ConfigurationParser parser = new ConfigurationParser(warnings);
        Configuration configuration = parser.parseConfiguration(configFile);
        DefaultShellCallback callback = new DefaultShellCallback(overwrite);
        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(configuration,callback,warnings);
        myBatisGenerator.generate(null);
    }

    public static void main(String[] args) throws InterruptedException, SQLException, InvalidConfigurationException, XMLParserException, IOException {
        Generator generator = new Generator();

        generator.generator();
    }
}

第二步:整合service層
通過 spring 管理 service 介面。
使用配置方式將 service 介面配置在 spring 配置檔案中。
實現事務控制

定義service介面

public interface ItemsService {
    //商品查詢列表
    List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo);
}

實現service介面

public class ItemsServiceImpl implements ItemsService {
    @Autowired
    private ItemsMapperCustom itemsMapperCustom;

    public List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo) {

        return itemsMapperCustom.findItemsList(itemsQueryVo);
    }
}

service配置
applicationContext-service

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

    <!--定義商品的service-->
    <bean class="com.demo.ssm.service.impl.ItemsServiceImpl">
    </bean>
</beans>

service事務宣告
applicationContext-tranaction.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:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"
>

    <!--事務管理器-->
    <!--對mybatis操作資料庫事務控制,是spring使用jdbc的事務控制類-->
    <bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!--資料來源
            dataSource在applicationContext-dao.xml中配置
        -->
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!--通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="save*" propagation="REQUIRED"/>
            <tx:method name="delete*" propagation="REQUIRED"/>
            <tx:method name="insert" propagation="REQUIRED"/>
            <tx:method name="update*" propagation="REQUIRED"/>
            <tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
            <tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
            <tx:method name="sel*" propagation="SUPPORTS" read-only="true"/>
        </tx:attributes>
    </tx:advice>

    <!--aop-->
    <aop:config>
        <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.demo.ssm.service.impl.*.*(..))"/>
    </aop:config>
</beans>

第三步:整合springmvc
由於 springmvc 是 spring 的模組 , 不需要整合。
建立 springmcv.xml,配置處理器對映器,介面卡,檢視解析器
springmvc.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:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"
>

    <!--對於註解的handler 可以單個配置
        實際開發中建議使用元件掃描
    -->
    <!--   <bean class="com.demo.ssm.controller.ItemsController3"></bean>-->

    <!--可以掃描 controller service-->
    <context:component-scan base-package="com.demo.ssm.controller"></context:component-scan>

    <!--處理器介面卡
        多個對映器可以並存

        所有的處理器介面卡都實現HandlerAdapter
    -->


    <!--註解對映器-->
    <!--spring 3.1之前 使用 org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping 註解對映器-->
    <!--spring 3.1 之後 使用 org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping 註解對映器-->

    <!--<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"></bean>-->

    <!--介面卡-->
    <!--spring 3.1 之前 使用 org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter 註解介面卡-->
    <!--spring 3.1 之後 使用 org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter 註解介面卡-->

    <!--<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"></bean>-->


    <!--使用 mvc:annotation-drien 可以代替上面註解對映器和註解介面卡的配置
        mvc:annotation-driven 預設載入了很多繫結方法 推薦使用
    -->
    <mvc:annotation-driven></mvc:annotation-driven>


    <!--試圖解析器-->
    <!--解析jsp檢視,預設使用jstl標籤,classpath需要jatl包-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

配置前端控制器
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>
  <!--載入spring容器-->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring/applicationContext-*.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!--通過contextConfigLocation配置springmvc載入配置檔案(配置處理對映器,介面卡)
        如果不配置,預設載入/WEB_INF/servlet名稱-servlet.xml(srpingmvc-servlet.xml)
    -->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc.xml</param-value>
    </init-param>
  </servlet>


  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <!--
        第一種: *.action 訪問以.action結尾由DispatcherServlet進行解析
        第二種: /         所有訪問的地址都由DispatcherServlet進行解析,對靜態檔案的解析需要配置,
        使用此方法可以實現restful風格url
        第三種: /*        錯誤配置方法,轉發jsp頁面仍由DispatcherServlet解析
    -->
    <url-pattern>*.action</url-pattern>
  </servlet-mapping>

</web-app>

編寫Controller(handler)
ItemsController.java

@Controller
public class ItemsController {
    @Autowired
    private ItemsService  itemsService;


    //商品查詢列表
    @RequestMapping("/queryItems")
    public ModelAndView queryItems(){
        List<ItemsCustom> list = itemsService.findItemsList(null);

        ;

        //返回modelAndView
        ModelAndView modelAndView = new ModelAndView();

        //相當於request的setAttr,在jsp通過itemlist獲取資料
        modelAndView.addObject("itemsList",list);

        //指定試圖
        //試圖解析器中配置了字首和字尾
//        modelAndView.setViewName("WEB-INF/jsp/itemsList.jsp");
        modelAndView.setViewName("itemsList");

        return modelAndView;

編寫jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@page isELIgnored="false" pageEncoding="UTF-8" %>
<%--
  Created by IntelliJ IDEA.
  User: v7
  Date: 2016/8/13
  Time: 12:18
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>ItemsList</title>
</head>
<body>
    <from action="${pageContext.request.contextPath }/item/queryItem.action" method="post">
        查詢條件:
        <table width="100%" border="1">
            <tr>
                <td><input type="submit" value="查詢"/></td>
            </tr>
        </table>
        商品列表:
        <table width="100%" border="1">
            <tr>
                <th>商品名稱</th>
                <th>商品價格</th>
                <th>生產日期</th>
                <th>商品描述</th>
                <th>操作</th>
            </tr>
            <c:forEach items="${itemsList}" var="item">
                <tr>
                    <td>${item.name}</td>
                    <td>${item.price}</td>
                    <td>${item.createTime}</td>
                    <td>${item.detail}</td>
                    <td><a href="${pageContext.request.contextPath}/item/editItem.action?id=${item.id}">修改</a></td>
                </tr>

            </c:forEach>
        </table>
    </from>
</body>
</html>

載入spring容器
將mapper,service,controller載入到spring中

建議使用萬用字元方法載入spring檔案.
在web.xml中,新增spring容器

  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring/applicationContext-*.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

所需要的jar包:
資料庫驅動包:mysql-5.1
mybatis 的jar包
mybatis 和 spring 整合包
log4j 包
資料庫連線池包 c3p0
spring 所以jar包
jstl包

maven pom.xml

<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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.demo</groupId>
  <artifactId>ssm</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>ssm Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>

    <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.38</version>
    </dependency>


    <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>4.3.2.RELEASE</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.2.2</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.2.8</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/junit/junit -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/log4j/log4j -->
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.17</version>
    </dependency>


    <!-- 新增Spring-core包 -->
             <dependency>
                 <groupId>org.springframework</groupId>
                 <artifactId>spring-core</artifactId>
                 <version>4.3.2.RELEASE</version>
             </dependency>
             <!-- 新增spring-context包 -->
             <dependency>
                 <groupId>org.springframework</groupId>
                 <artifactId>spring-context</artifactId>
                 <version>4.3.2.RELEASE</version>
             </dependency>
             <!-- 新增spring-tx包 -->
             <dependency>
                 <groupId>org.springframework</groupId>
                 <artifactId>spring-tx</artifactId>
                 <version>4.3.2.RELEASE</version>
             </dependency>
             <!-- 新增spring-jdbc包 -->
             <dependency>
                 <groupId>org.springframework</groupId>
                 <artifactId>spring-jdbc</artifactId>
                 <version>4.3.2.RELEASE</version>
             </dependency>
             <!-- 為了方便進行單元測試,新增spring-test包 -->
             <dependency>
                 <groupId>org.springframework</groupId>
                 <artifactId>spring-test</artifactId>
                 <version>4.3.2.RELEASE</version>
             </dependency>
             <!--新增spring-web包 -->
             <dependency>
                 <groupId>org.springframework</groupId>
                 <artifactId>spring-web</artifactId>
                 <version>4.3.2.RELEASE</version>
             </dependency>
             <!--新增aspectjweaver包 -->
             <dependency>
                 <groupId>org.aspectj</groupId>
                 <artifactId>aspectjweaver</artifactId>
                 <version>1.8.5</version>
             </dependency>

    <!-- https://mvnrepository.com/artifact/c3p0/c3p0 -->
    <dependency>
      <groupId>c3p0</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.1.2</version>
    </dependency>


    <!-- https://mvnrepository.com/artifact/org.mybatis.generator/mybatis-generator-core -->
    <dependency>
      <groupId>org.mybatis.generator</groupId>
      <artifactId>mybatis-generator-core</artifactId>
      <version>1.3.2</version>
    </dependency>

      <!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
      <dependency>
          <groupId>javax.servlet</groupId>
          <artifactId>jstl</artifactId>
          <version>1.2</version>
      </dependency>



  </dependencies>


  <build>
    <finalName>ssm</finalName>

    <plugins>
      <plugin>
        <groupId>org.mybatis.generator</groupId>
        <artifactId>mybatis-generator-maven-plugin</artifactId>
        <version>1.3.2</version>
        <configuration>
          <verbose>true</verbose>
          <overwrite>true</overwrite>
        </configuration>
      </plugin>

    </plugins>

    <resources>
      <resource>
        <directory>
          src/main/resources
        </directory>
      </resource>
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.xml</include>
        </includes>
      </resource>
    </resources>
  </build>
</project>

db.properties

jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/mdb?charaterEncoding='UTF-8'&useSSL=true
jdbc.username = root
jdbc.password = root

log4j.properties

# Global logging configuration
#在開發環境下級別設定成DEBUG,生成環境設定成info或error
log4j.rootLogger = debug,stdout
# MyBatis logging configuration...
log4j.logger.test=TRACE

### 輸出資訊到控制擡 ###
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=%5p [%t] - %m%n