SSM 整合

2020-08-09 00:37:39

本專案github地址:https://github.com/syq524718898/ssmproject.git

SSM是什麼?

SSM(Spring+SpringMVC+MyBatis)框架集由Spring、MyBatis兩個開源框架整合而成(SpringMVC是Spring中的部分內容)

三層架構

我們的開發架構一般都是基於兩種形式,一種是 C/S 架構,也就是用戶端/伺服器,另一種是 B/S 架構,也就 是瀏覽器伺服器。在 JavaEE 開發中,幾乎全都是基於 B/S 架構的開發。那麼在 B/S 架構中,系統標準的三層架構包括:表現層、業務層、持久層。

三層架構中,每一層各司其職:
表現層
也就是我們常說的web層。它負責接收用戶端請求,向用戶端響應結果,通常用戶端使用http協定請求 web 層,web 需要接收 http 請求,完成 http 響應。
表現層包括展示層和控制層:控制層負責接收請求,展示層負責結果的展示。
表現層依賴業務層,接收到用戶端請求一般會呼叫業務層進行業務處理,並將處理結果響應給用戶端。
表現層的設計一般都使用 MVC 模型。(MVC是表現層的設計模型,和其他層沒有關係)

業務層
也就是我們常說的 service 層。它負責業務邏輯處理,和我們開發專案的需求息息相關。
web層依賴業務層,但是業務層不依賴 web 層。
業務層在業務處理時可能會依賴持久層,如果要對數據持久化需要保證事務一致性。(也就是我們說的,事務應該放到業務層來控制)

持久層
也就是我們是常說的 dao 層。負責數據持久化,包括數據層即數據庫和數據存取層,數據庫是對數據進行持久化的載體,數據存取層是業務層和持久層互動的介面,業務層需要通過數據存取層將數據持久化到數據庫中。通俗的講,持久層就是和數據庫互動,對數據庫表進行曾刪改查的

MVC 模型

MVC 全名是 Model View Controller,是模型(model)-檢視(view)-控制器(controller)的縮寫,是一種用於設計建立 Web 應用程式表現層的模式。MVC 中每個部分各司其職:
Model(模型)
通常指的就是我們的數據模型。作用一般情況下用於封裝數據。
View(檢視):
通常指的就是我們的 jsp 或者 html。作用一般就是展示數據的。
通常檢視是依據模型數據建立的。
Controller(控制器):
是應用程式中處理使用者互動的部分。作用一般就是處理程式邏輯的。

SpringMVC

SpringMVC是一種基於 Java 的實現 MVC 設計模型的請求驅動型別的輕量級 Web 框架,屬於 Spring FrameWork的後續產品,已經融合在Spring Web Flow裏面。Spring框架提供了構建 Web 應用程式的全功能 MVC 模組。使用 Spring 可插入的 MVC 架構,從而在使用 Spring 進行 WEB 開發時,可以選擇使用 Spring 的 Spring MVC 框架或整合其他 MVC 開發框架,如Struts1(現在一般不用),Struts2等。

SpringMVC 已經成爲目前最主流的 MVC 框架之一,並且隨着 Spring3.0 的發佈,全面超越 Struts2,成爲最優秀的 MVC 框架。

它通過一套註解,讓一個簡單的 Java 類成爲處理請求的控制器,而無須實現任何介面。同時它還支援 RESTful 程式設計風格的請求 。


下面 下麪我們通過一個案例來進行SSM的整合

整合SSM

整合說明:SSM整合採用XML + 註解的方式

環境準備

建立數據庫和表結構

# mysql 版本爲8.0以上
 create database ssm_project;
 use ssm_project;
 create table account(id int primary key auto_increment,name varchar(20),money float);

插入一些數據

insert into account values(null,"jack",2000),(null,"marry",3000),(null,"kasa",1500),(null,"lina",4000),(null,"mack",5000),(null,"linda",6000),(null,"tina",4000),(null,"ethan",6000),(null,"james",3000),(null,"noah",7000),(null,"samuel",5500),(null,"jack",4000);

建立 Maven 工程
匯入座標並建立依賴
pom.xml

<?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>cn.itcast</groupId>
  <artifactId>ssm</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>ssm 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.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <spring.version>5.0.2.RELEASE</spring.version>
    <mysql.version>8.0.11</mysql.version>
    <mybatis.version>3.4.5</mybatis.version>
  </properties>

  <dependencies>
    <!-- spring -->
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.6.8</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</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-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</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>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>compile</scope>
    </dependency>

    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>${mysql.version}</version>
    </dependency>

    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.5</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.0</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>

    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>${mybatis.version}</version>
    </dependency>

    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.0</version>
    </dependency>

    <dependency>
      <groupId>c3p0</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.1.2</version>
      <type>jar</type>
      <scope>compile</scope>
    </dependency>
  </dependencies>

  <build>
    <finalName>ssm</finalName>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.0.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.7.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.20.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

編寫賬戶實體類

package domain;
import java.io.Serializable;

/**
 * 帳戶
 */
public class Account implements Serializable{

    private Integer id;
    private String name;
    private Float money;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Float getMoney() {
        return money;
    }

    public void setMoney(Float money) {
        this.money = money;
    }

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money=" + money +
                '}';
    }
}

編寫分頁實體類

package domain;

import java.util.List;

/**
 * 分頁物件
 */
public class PageBean<T> {
    private int totalCount; // 總記錄數
    private int totalPage ; // 總頁碼
    private List<T> list ; // 每頁的數據
    private int currentPage ; //當前頁碼
    private int rows=5;//每頁顯示的記錄數

    public int getTotalCount() {
        return totalCount;
    }

    public void setTotalCount(int totalCount) {
        this.totalCount = totalCount;
    }

    public int getTotalPage() {
        return totalPage;
    }

    public void setTotalPage(int totalPage) {
        this.totalPage = totalPage;
    }

    public List<T> getList() {
        return list;
    }

    public void setList(List<T> list) {
        this.list = list;
    }

    public int getCurrentPage() {
        return currentPage;
    }

    public void setCurrentPage(int currentPage) {
        this.currentPage = currentPage;
    }

    public int getRows() {
        return rows;
    }

    public void setRows(int rows) {
        this.rows = rows;
    }

    @Override
    public String toString() {
        return "PageBean{" +
                "totalCount=" + totalCount +
                ", totalPage=" + totalPage +
                ", list=" + list +
                ", currentPage=" + currentPage +
                ", rows=" + rows +
                '}';
    }
}

編寫dao介面

package dao;

import domain.Account;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 帳戶dao介面
 */
@Repository
public interface AccountDao {

    //查詢賬戶
    @Select("select * from account limit #{start},#{count}")
    List<Account> findAll(@Param("start")Integer start,@Param("count")Integer count);

    //儲存賬戶
    @Insert("insert into account (name,money) values (#{name},#{money})")
    void saveAccount(Account account);

    //更新賬戶
    @Update("update account set name=#{name},money=#{money} where id=#{id}")
    int updateAccount(Account account);

    //刪除賬戶
    @Delete("delete from account where id=#{acccountId}")
    int deleteAccount(Integer acccountId);


    //根據名稱查詢賬戶
    @Select("select * from account where name=#{accountName} limit #{start},#{count}")
    List<Account> findAccountByName(@Param("accountName") String accountName,@Param("start") Integer start,@Param("count") Integer count);

    //根據ID查詢賬戶
    @Select("select * from account where id=#{accountid}")
    Account findAccountById(Integer accountid);

    //查詢記錄數
    @Select("select count(*) from account")
    Integer findTotal();

    //查詢滿足條件的記錄數
    @Select("select count(*) from account where name=#{name}")
    Integer findTotalbyname(String name);
}

編寫service介面和實現類

service介面

package service;

import domain.Account;
import java.util.List;

public interface AccountService {

    List<Account> findAll(Integer start,Integer count);

    void saveAccount(Account account);

    void updateAccount(Account account);

    void deleteAccount(Integer accountId);

    List<Account> findAccountByName(String accountName,Integer start,Integer count);

    Account findAccountById(Integer accountid);

    Integer findTotal();

    Integer findTotalbyname(String name);
}

service實現類

package service.impl;

import dao.AccountDao;
import domain.Account;
import service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service("accountService")
public class AccountServiceImpl implements AccountService{

    @Autowired
    private AccountDao accountDao;
    @Override
    public List<Account> findAll(Integer start,Integer count) {
        return accountDao.findAll(start,count);
    }
    @Override
    public void saveAccount(Account account) {
        accountDao.saveAccount(account);
    }
    @Override
    public void updateAccount(Account account) {
        accountDao.updateAccount(account);
    }
    @Override
    public void deleteAccount(Integer accountId) {
        accountDao.deleteAccount(accountId);
    }
    @Override
    public List<Account> findAccountByName(String accountName,Integer start,Integer count) {
        return accountDao.findAccountByName(accountName,start,count);
    }
    @Override
    public Account findAccountById(Integer accountid) {
        return accountDao.findAccountById(accountid);
    }
    @Override
    public Integer findTotal() {
        return accountDao.findTotal();
    }
    @Override
    public Integer findTotalbyname(String name) {
        return accountDao.findTotalbyname(name);
    }
}

Spring整合MyBatis框架

建立applicationContext.xml的組態檔,整合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"
       xmlns:aop="http://www.springframework.org/schema/aop"
       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/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">

    <!--開啓註解的掃描,希望處理service和dao,controller不需要Spring框架去處理-->
    <context:component-scan base-package="controller,dao,domain,service" >
        <!--設定哪些註解不掃描-->
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
    </context:component-scan>

    <!--Spring整合MyBatis框架-->
    <!--設定連線池-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.cj.jdbc.Driver"/>
        <property name="jdbcUrl" value="jdbc:mysql:///ssm_project?useUnicode=true&amp;serverTimezone=GMT&amp;useSSL=false"/>
        <property name="user" value="root"/>
        <property name="password" value="qwe123"/>
    </bean>

    <!--設定SqlSessionFactory工廠-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!--設定AccountDao介面所在包-->
    <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="dao"/>
    </bean>

    <!--設定Spring框架宣告式事務管理-->
    <!--設定事務管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!--設定事務通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="find*" read-only="true"/>
            <tx:method name="*" isolation="DEFAULT"/>
        </tx:attributes>
    </tx:advice>

    <!--設定AOP增強-->
    <aop:config>
        <aop:advisor advice-ref="txAdvice" pointcut="execution(* service.impl.*ServiceImpl.*(..))"/>
    </aop:config>
</beans>

建立springmvc.xml的組態檔,編寫組態檔

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
       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
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    <!--開啓註解掃描,只掃描Controller註解-->
    <context:component-scan base-package="controller,dao,domain,service">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
    </context:component-scan>

    <!--設定的檢視解析器物件-->
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <!--過濾靜態資源-->
    <mvc:resources location="/css/" mapping="/css/**" />
    <mvc:resources location="/images/" mapping="/images/**" />
    <mvc:resources location="/js/" mapping="/js/**" />

    <!--開啓SpringMVC註解的支援-->
    <mvc:annotation-driven/>
</beans>

Spring整合SpringMVC框架

在web.xml中設定DispatcherServlet前端控制器,同時設定DispatcherServlet過濾器解決中文亂碼,載入spring組態檔

<!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的監聽器,預設只載入WEB-INF目錄下的applicationContext.xml組態檔-->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <!--設定組態檔的路徑-->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>

  <!--設定前端控制器-->
  <servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!--載入springmvc.xml組態檔-->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc.xml</param-value>
    </init-param>
    <!--啓動伺服器,建立該servlet-->
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/</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>
  </filter>
  <filter-mapping>
    <filter-name>characterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

建立控制器AccountController類

package controller;

import domain.Account;
import domain.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import service.AccountService;

/**
 * 帳戶web
 */
@Controller
@RequestMapping("/account")
public class AccountController {

    @Autowired
    private AccountService accountService;

    @RequestMapping("add")
    public String add()
    {
        return "add";
    }

    @RequestMapping("/addAccount")
    public String save(Account account)
    {
        accountService.saveAccount(account);
        return "redirect:/account/findAll";
    }

    @RequestMapping("/update")
    public String update(Integer id,Model model)
    {
        Account accountById = accountService.findAccountById(id);
        model.addAttribute("account",accountById);
        return "update";
    }

    @RequestMapping("/updatesubmit")
    public String updatesubmit(Account account)
    {
        accountService.updateAccount(account);
        return "redirect:/account/findAll";
    }

    @RequestMapping("findAll")
    public String findAll(Integer page,String name,Model model)
    {
        PageBean<Account> pb = new PageBean<>();
        if (page==null || "".equals(page))
        {
            pb.setCurrentPage(1);
        }
        else
        {
            pb.setCurrentPage(page);
        }

        if (name==null || "".equals(name))
        {
            pb.setList(accountService.findAll((pb.getCurrentPage()-1)*pb.getRows(),pb.getRows()));
            pb.setTotalCount(accountService.findTotal());
            pb.setTotalPage(pb.getTotalCount()%pb.getRows()==0?pb.getTotalCount()/pb.getRows():pb.getTotalCount()/pb.getRows()+1);
        }
        else
        {
            pb.setList(accountService.findAccountByName(name,(pb.getCurrentPage()-1)*pb.getRows(),pb.getRows()));
            pb.setTotalCount(accountService.findTotalbyname(name));
            pb.setTotalPage(pb.getTotalCount()%pb.getRows()==0?pb.getTotalCount()/pb.getRows():pb.getTotalCount()/pb.getRows()+1);
        }
        model.addAttribute("condion",name);
        model.addAttribute("pb",pb);
        return "list";
    }

    @RequestMapping("delAccount")
    public String delAccount(Integer id)
    {
        accountService.deleteAccount(id);
        return "redirect:/account/findAll";
    }

    @RequestMapping("delSelect")
    public String delSelect(String[] aid)
    {
        for (String id : aid) {
            accountService.deleteAccount(Integer.parseInt(id));
        }
        return "redirect:/account/findAll";
    }
}

前端檔案這裏就不展示了,專案github地址:https://github.com/syq524718898/ssmproject.git
歡迎存取

專案效果演示

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

今天的分享就到這兒了,希望大家能夠有所收穫,歡迎關注。