SpringMVC-整合SSM

weixin_44961111發表於2020-09-28

1. 搭建整合環境

思路:

  1. 先搭建整合的環境
  2. 先把Spring的配置搭建完成
  3. 再使用Spring整合SpringMVC框架
  4. 最後使用Spring整合MyBatis框架

1.1建立資料庫和資料表

create database ssm;
use ssm;
create table account(
id int primary keyauto_increment,
name varchar(20),
money double );

1.2 建立maven工程,匯入相關座標

 <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>
        <slf4j.version>1.6.6</slf4j.version>
        <log4j.version>1.2.12</log4j.version>
        <mysql.version>5.1.6</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>
        </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>
        <!-- log start -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>${log4j.version}</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 -->
        <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>

1.3 編寫實體類

package com.feilong.entity;

import java.io.Serializable;

/**
 * @author FeiLong
 * @version 1.8
 * @date 2020/9/28 16:50
 * <p>
 * 賬戶實體類
 */
@SuppressWarnings("ALL")
public class Account implements Serializable {
    private int id;
    private String name;
    private float money;

    public Account() {
    }

    public Account(String name, float money) {
        this.name = name;
        this.money = money;
    }

    public int getId() {
        return id;
    }

    public void setId(int 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 +
                '}';
    }
}

1.4 編寫dao介面

package com.feilong.dao;

import com.feilong.entity.Account;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author FeiLong
 * @version 1.8
 * @date 2020/9/28 16:52
 * 賬戶的持久層
 */
@SuppressWarnings("ALL")
@Repository
public interface AccountDao {
    /**
     * 查詢所有
     *
     * @return
     */
    @Select("select * from account")
    List<Account> findAll();

    /**
     * 根據賬戶id查詢
     *
     * @param id
     * @return
     */
    Account findAccountById(int id);

    /**
     * 儲存使用者
     * @param account
     */
    @Insert("insert into account(name,money) values(#{name},#{money})")
    void insertAccount(Account account);
}


1.5 編寫service介面和實現類


package com.feilong.service;

import com.feilong.entity.Account;

import java.util.List;

/**
 * @author FeiLong
 * @version 1.8
 * @date 2020/9/28 16:54
 */
@SuppressWarnings("ALL")
public interface AccountService {
    /**
     * 查詢所有
     *
     * @return
     */
    List<Account> findAll();

    /**
     * 根據賬戶id查詢
     *
     * @param id
     * @return
     */
    Account findAccountById(int id);

    /**
     * 儲存使用者
     *
     * @param account
     */
    void insertAccount(Account account);
}

package com.feilong.service.impl;

import com.feilong.dao.AccountDao;
import com.feilong.entity.Account;
import com.feilong.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author FeiLong
 * @version 1.8
 * @date 2020/9/28 16:55
 * 賬戶的業務層實現類
 */
@SuppressWarnings("ALL")
@Service("accountService")
public class AccountServiceImpl implements AccountService {
    @Autowired
    private AccountDao accountDao;

    @Override
    public List<Account> findAll() {
        List<Account> accounts = accountDao.findAll();
        return accounts;
    }

    @Override
    public Account findAccountById(int id) {
        Account account = accountDao.findAccountById(id);
        return account;
    }

    @Override
    public void insertAccount(Account account) {
        accountDao.insertAccount(account);

    }
}

2.Spring框架程式碼的編寫

2.1 編寫配置檔案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"
       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">
    <!--開啟註解掃描
      此處配置的是掃描dao層和service層的註解,忽略web層
      controller層交給SpringMVC管理
    -->
    <context:component-scan base-package="com.feilong">
        <!--配置要忽略的註解-->
        <context:exclude-filter type="annotation"
                                expression="org.springframework.stereotype.Controller"></context:exclude-filter>
    </context:component-scan>

//Spring整合MyBatis框架

    <!--配置C3P0的連線池物件-->
    <bean id="comboPooledDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql://cdb-jm1yf68w.cd.tencentcdb.com:10178/spring"></property>
        <property name="user" value="root"></property>
        <property name="password" value="xmw225310"></property>
    </bean>
    <!--配置SqlSession的工廠-->
    <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="comboPooledDataSource"></property>
    </bean>
    <!--配置需要掃描的dao包-->
    <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.feilong.dao"></property>
    </bean>

//配置Spring的宣告式事務管理
    <!--配置事務管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
       <!--注入資料來源-->
        <property name="dataSource" ref="comboPooledDataSource"></property>
    </bean>
    <!--配置事務通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
            <tx:method name="*" propagation="REQUIRED" read-only="false"/>
        </tx:attributes>
    </tx:advice>
    <!--配置AOP-->
    <aop:config>
        <!--建立切入點表示式與通知之間的關係-->
        <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.feilong.service.impl.*.*(..))"/>
    </aop:config>
</beans>

3.Spring整合SpringMVC框架

3.1配置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>
    <!--配置中文亂碼的過濾器-->
    <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>
    <!--配置SpringMVC的核心控制器-->
    <!--配置前端控制器-->
    <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- 配置Servlet的初始化引數,讀取springmvc的配置檔案,建立spring容器 -->
        <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>


//  Spring整合SpringMVC的框架
    <!--配置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>
</web-app>

3.2 建立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">
    <!--開啟SpringMVC的註解掃描,只掃描controller層-->
    <context:component-scan base-package="com.feilong">
        <context:include-filter type="annotation"
                                expression="org.springframework.stereotype.Controller"></context:include-filter>
    </context:component-scan>
    <!--配置檢視解析器-->
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--JSP檔案所在的目錄-->
        <property name="prefix" value="/WEB-INF/pages/"></property>
        <!--檔案的字尾名-->
        <property name="suffix" value=".jsp"></property>
    </bean>
    <!--配置靜態資源不過濾-->
    <mvc:resources mapping="/css/**" location="/css/"/>
    <mvc:resources mapping="/js/**" location="/js/"/>
    <mvc:resources mapping="/images/**" location="/images/"/>

    <!--開啟註解對mvc的支援-->
    <mvc:annotation-driven/>

</beans>

4.編寫控制器開始測試

package com.feilong.controller;

import com.feilong.entity.Account;
import com.feilong.service.AccountService;
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 java.util.List;

/**
 * @author FeiLong
 * @version 1.8
 * @date 2020/9/28 16:58
 * 賬戶的控制層
 */
@SuppressWarnings("ALL")
@Controller
@RequestMapping("/account")
public class AccountController {

    @Autowired
    private AccountService accountService;

    /**
     * 查詢所有
     *
     * @param model
     * @return
     */
    @RequestMapping("/findAll")
    public String findAll(Model model) {
        System.out.println("表現層list...");
        List<Account> accounts = accountService.findAll();
        accounts.forEach(System.out::println);
        model.addAttribute("accounts", accounts);
        return "list";
    }

    /**
     * 新增使用者
     *
     * @param account
     * @return
     */
    @RequestMapping("/insertAccount")
    public String insertAccount(Account account) {
        accountService.insertAccount(account);
        return "redirect:/account/findAll";
    }
}

完成!

相關文章