1. 程式人生 > 實用技巧 >整合SSM框架

整合SSM框架

整合SSM

基本環境搭建

匯入相關的pom依賴!

<dependencies>
        <!--Junit-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <!--資料庫驅動-->
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.18</version> </dependency> <!-- 資料庫連線池 --> <dependency> <groupId
>com.mchange</groupId> <artifactId>c3p0</artifactId> <version>0.9.5.2</version> </dependency> <!--Servlet - JSP --> <dependency> <groupId>javax.servlet</groupId> <artifactId
>servlet-api</artifactId> <version>2.5</version> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.2</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!--Mybatis--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.2</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>2.0.2</version> </dependency> <!--Spring--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.1.9.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.1.9.RELEASE</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.16.10</version> </dependency> </dependencies>

Maven資源過濾設定

<!--靜態資源匯出問題  -->
    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>

建立基本結構和配置框架!

  • com.kuang.pojo

  • com.kuang.dao

  • com.kuang.service

  • com.kuang.controller

  • mybatis-config.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>

</configuration>

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

</beans>

Mybatis層編寫

資料庫配置檔案 database.properties

我用的是8.0的mysql資料庫連線版本,加cj同時要加上時區設定

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssmbook?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT
jdbc.username=root
jdbc.password=fengge666

編寫MyBatis的核心配置檔案

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

    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>
    
    <typeAliases>
        <package name="com.xlf.pojo"/>
    </typeAliases>

    <mappers>
        <mapper class="com.xlf.dao.BookMapper" />
    </mappers>

</configuration>

編寫資料庫對應的實體類

使用lombok外掛!

package com.xlf.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Books {

    private int bookID;
    private String bookName;
    private int bookCounts;
    private String details;


}

編寫Dao層的 Mapper介面!

package com.xlf.dao;

import com.xlf.pojo.Books;
import org.apache.ibatis.annotations.Param;
import org.junit.runners.Parameterized;

import java.util.List;

public interface BookMapper {

    //增加一本書
    int addBook(Books books);

    //刪除一本書
    int deleteBookById(@Param("bookId") int id);

    //更新一本書
    int updateBook(Books books);

    //查詢一本書
    Books queryBookById(int id);

    //查詢全部的書
    List<Books> queryAllBook();
    
    //模糊搜尋
    List<Books> queryBookByName(String bookName);



}

編寫介面對應的 Mapper.xml 檔案

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.xlf.dao.BookMapper">

    <insert id="addBook" parameterType="Books">
        insert into books (bookName,bookCounts,details) value (#{bookName},#{bookCounts},#{details});
    </insert>

    <delete id="deleteBookById" parameterType="int">
        delete from books where bookID=#{bookId};
    </delete>

    <update id="updateBook" parameterType="Books">
        update books set bookName=#{bookName},bookCounts=#{bookCounts},details=#{details} where bookID=#{bookID};
    </update>

    <select id="queryBookById" parameterType="int" resultType="Books">
        select * from books where bookID=#{id};
    </select>

    <select id="queryAllBook" resultType="Books">
        select * from books;
    </select>

    <select id="queryBookByName" resultType="Books">
        select * from books where bookName like concat('%','${bookName}','%');
    </select>
    
</mapper>

編寫Service層的介面和實現類

介面:

package com.xlf.service;

import com.xlf.pojo.Books;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface BookService {

    //增加一本書
    int addBook(Books books);

    //刪除一本書
    int deleteBookById(int id);

    //更新一本書
    int updateBook(Books books);

    //查詢一本書
    Books queryBookById(int id);

    //查詢全部的書
    List<Books> queryAllBook();

    //模糊搜尋
    List<Books> queryBookByName(String bookName);


}

實現類:

package com.xlf.service;

import com.xlf.dao.BookMapper;
import com.xlf.pojo.Books;

import java.util.List;

public class BookServiceImpl implements BookService {
    //service調dao層:組合Dao
    private BookMapper bookMapper;

    public void setBookMapper(BookMapper bookMapper) {
        this.bookMapper = bookMapper;
    }

    public int addBook(Books books) {
        return bookMapper.addBook(books);
    }

    public int deleteBookById(int id) {
        return bookMapper.deleteBookById(id);
    }

    public int updateBook(Books books) {
        return bookMapper.updateBook(books);
    }

    public Books queryBookById(int id) {
        return bookMapper.queryBookById(id);
    }

    public List<Books> queryAllBook() {
        return bookMapper.queryAllBook();
    }

    public List<Books> queryBookByName(String bookName) {
        return bookMapper.queryBookByName(bookName);
    }
}

Spring層編寫

配置Spring整合MyBatis,我們這裡資料來源使用c3p0連線池;

我們去編寫Spring整合Mybatis的相關的配置檔案;spring-dao.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"
       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">

    <!--關聯資料庫配置操作 -->
    <context:property-placeholder location="classpath:database.properties" />

    <!--2.連線池 -->
    <!--資料庫連線池
       dbcp 半自動化操作 不能自動連線
       c3p0 自動化操作(自動的載入配置檔案 並且設定到物件裡面)
   -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}" />
        <property name="jdbcUrl" value="${jdbc.url}" />
        <property name="user" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />

        <!-- c3p0連線池的私有屬性 -->
        <property name="maxPoolSize" value="30"/>
        <property name="minPoolSize" value="10"/>
        <!-- 關閉連線後不自動commit -->
        <property name="autoCommitOnClose" value="false"/>
        <!-- 獲取連線超時時間 -->
        <property name="checkoutTimeout" value="10000"/>
        <!-- 當獲取連線失敗重試次數 -->
        <property name="acquireRetryAttempts" value="2"/>

    </bean>

    <!--3.sqlSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!--繫結Mybatis的配置檔案 -->
        <property name="configLocation" value="classpath:mybatis-config.xml" />
    </bean>

    <!--配置dao的介面掃描包,動態實現Dao介面可以注入到Spring容器中 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 注入sqlSessionFactory-->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
        <!--要掃描的dao包 -->
        <property name="basePackage" value="com.xlf.dao" />
    </bean>

</beans>

Spring整合service層

spring-service.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 掃描service下的包-->
    <context:component-scan base-package="com.xlf.service" />


    <!-- 將我們所有的業務類,注入到Spring,可以通過配置或註解實現-->
    <bean id="BookServiceImpl" class="com.xlf.service.BookServiceImpl">
        <property name="bookMapper" ref="bookMapper" />
    </bean>

    <!--宣告式事務配置 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />

    </bean>

</beans>

SpringMVC層

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

    <!-- DispatcherServlet-->
    <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:applicationContext.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!--亂碼過濾 -->
    <filter>
        <filter-name>encodingFilter</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>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!--Session -->
    <session-config>
        <session-timeout>15</session-timeout>
    </session-config>


</web-app>

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

    <!--1.註解驅動 -->
    <mvc:annotation-driven />
    <!--2.靜態資源過濾 -->
    <mvc:default-servlet-handler />
    <!--3.掃描包:controller -->
    <context:component-scan base-package="com.xlf.controller" />
    <!--4.檢視解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>

</beans>

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

    <import resource="classpath:spring-dao.xml" />
    <import resource="classpath:spring-mvc.xml" />
    <import resource="classpath:spring-service.xml" />

</beans>

配置檔案,暫時結束!

Controller 和 檢視層編寫

BookController 類編寫

package com.xlf.controller;


import com.xlf.pojo.Books;
import com.xlf.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Controller
@RequestMapping("/book")
public class BookController {

    @Autowired
    @Qualifier("BookServiceImpl")
    private BookService bookService;

    //查詢全部的書籍,返回到一個書籍展示頁面
    @RequestMapping("/allBook")
    public String list(Model model)
    {
        List<Books> list=bookService.queryAllBook();
        model.addAttribute("list",list);
        return "allBook";
    }

    //跳轉到增加書籍頁面
    @RequestMapping("/toAddBook")
    public String toAddPaper()
    {
        return "addBook";
    }

    @RequestMapping("/addBook")
    public String addBook(Books books)
    {
        System.out.println("addBook=>"+books);
        bookService.addBook(books);
        return "redirect:/book/allBook";
    }

    @RequestMapping("/toUpdate")
    public String toUpdatePaper(int id,Model model)
    {
        Books books=bookService.queryBookById(id);
        model.addAttribute("QBook",books);
        return "updateBook";
    }

    @RequestMapping("/updateBook")
    public String updateBook(Books books)
    {
        System.out.println("updateBook->"+books);
        bookService.updateBook(books);
        return "redirect:/book/allBook";
    }

    @RequestMapping("/deleteBook/{bookId}")
    public String deleteBook(@PathVariable("bookId") int id)
    {
        bookService.deleteBookById(id);
        return "redirect:/book/allBook";
    }

    @RequestMapping("/queryBook")
    public String queryBook(String queryBookName,Model model)
    {
        List<Books> list = bookService.queryBookByName(queryBookName);
        if (list.size()==0)
        {
            list=bookService.queryAllBook();
            model.addAttribute("error","未找到");
        }
        model.addAttribute("list",list);
        return "allBook";
    }

}

前臺頁面就不在展示了,過於簡譜,重點在於理解ssm框架的整合流程

執行展示

展示結果

執行結果如下所示:

專案的結構圖

總結

學習之後,狂神的配置流程很清晰,期間也出現過錯誤,有錯才能進步,才知道這個報錯的原因是啥?學到很多知識。日後還要繼續學習ssm框架,打算學完後,將自己之前的專案用SSM框架整一遍。

熟練的應用這套框架,我個人還是喜歡用html頁面來做,之後要嘗試把jsp全部換成html來開發。

過幾天,就要考毛概了,該開始準備預習了。。。。