2021-07-22ssm整合最全篇

  • 时间:
  • 浏览:
  • 来源:互联网

一.搭建整合环境

1.整合说明:

SSM整合可以使用多种方式,选择XML + 注解的方式

2.整合的思路

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

3.导入依赖

<?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.tf</groupId>
  <artifactId>ssm1</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>ssm1 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.2.2.RELEASE</spring.version>
    <slf4j.version>1.6.6</slf4j.version>
    <log4j.version>1.2.12</log4j.version>
    <mysql.version>6.0.3</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>4.3.30.RELEASE</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>5.1.47</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>

  <build>
    <finalName>ssm1</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.1.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.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.2</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>

4.编写包名与类

1.编写domain类

package cn.tf.domain;

import java.io.Serializable;

/**
 * 账户信息
 */
public class Account implements Serializable {

    private Integer id;
    private String name;
    private Double 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 Double getMoney() {
        return money;
    }

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

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

2.编写dao接口

package cn.tf.dao;

import cn.tf.domain.Account;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 用户的
 */
@Repository
public interface AccountDao {

    /**
     * 查询所有账户
     * @return
     */
    @Select("select * from account")
    public List<Account> findAll();

    /**
     * 保存账户信息
     * @param account
     */
    @Insert("insert into account(name,money) values(#{name},#{money})")
    public void saveAccount(Account account);
}

3.编写service接口和实现类

package cn.tf.service;

import cn.tf.domain.Account;

import java.util.List;

public interface AccountService {

    /**
     * 查询所有账户
     * @return
     */
    public List<Account> findAll();

    /**
     * 保存账户信息
     * @param account
     */
    public void saveAccount(Account account);
}

package cn.tf.service.impl;

import cn.tf.dao.AccountDao;
import cn.tf.domain.Account;
import cn.tf.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 {

    private AccountDao accountDao;

    /**
     * 把accountDao注进service,这样就可以调用accountDao里面的方法
     */
    @Autowired
    public void setAccountDao(AccountDao accountDao) {
        this.accountDao = accountDao;
    }

    @Override
    public List<Account> findAll() {
        System.out.println("业务层:查询了所有账户...");
        return accountDao.findAll();
    }

    @Override
    public void saveAccount(Account account) {
        System.out.println("业务层:保存了所有账户...");
        accountDao.saveAccount(account);
    }
}

二.spring框架的搭建

1.配置spring-config.xml

 <!--开启扫描,扫描的都是要注解的-->
<context:component-scan base-package="cn.tf">
    <!--只扫描dao和service层的内容,控制层不需要进行扫描,controller用springmvc去处理-->
    <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

2.在类上加注解

@Service("accountService")
public class AccountServiceImpl implements AccountService {
    @Override
    public List<Account> findAll() {
        System.out.println("业务层:查询了所有账户...");
        return null;
    }

    @Override
    public void saveAccount(Account account) {
        System.out.println("业务层:保存了所有账户...");
    }
}

3.测试spring的环境

public class TestSpring {

    @Test
    public void findAll(){

        //加载配置文件
        ApplicationContext ac=new ClassPathXmlApplicationContext("classpath:spring-config.xml");
        //获取对象
        AccountService as=(AccountService) ac.getBean("accountService");
        //调用方法
        as.findAll();
    }
}

三.springMVC框架的搭建

1.在web.xml中添加前端控制器

1.包括加载spring-mvc配置文件和启动服务器

<!--配置前端控制器-->
<servlet>
  <servlet-name>dispatcherServlet</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <!--加载spring-mvc这个配置文件,首先要进行初始化-->
  <init-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring-mvc.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>

2.解决中文乱码的过滤器

<!--2.解决中文乱码的过滤器,/*表示什么都进行拦截-->
<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>

3.配置spring-mvc.xml的配置文件

1.开启注解扫描,只扫描controller注解

<!--开启注解扫描,只扫描controller注解-->
<context:component-scan base-package="cn.tf">
    <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

2.配置视图解析器对象

<!--配置视图解析器对象-->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/pages"></property>
    <property name="suffix" value=".jsp"></property>
</bean>

3.过滤静态资源

<!--过滤静态资源-->
<mvc:resources location="/css/" mapping="/css/**" />
<mvc:resources location="/images/" mapping="/images/**" />
<mvc:resources location="/js/" mapping="/js/**" />

4.开启spring-mvc注解的支持

<!--开启spring-mvc注解的支持-->
<mvc:annotation-driven></mvc:annotation-driven>

4.测试控制器

@Controller
@RequestMapping("account")  //设置一级请求目录
public class AccountController {

    @RequestMapping("/findAll")   //设置二级请求目录
    public String findAll(){
        System.out.println("表现层:查询所有执行了.....");
        return "list";   //返回list,这是根据视图解析器来解析WEB-INF/pages下面的.jsp文件
    }
}

四.spring整合springMVC

创建监听器,用来加载spring的配置文件,启动服务器,加载spring配置文件,在控制器中注入service业务层。

1.在web.xml中配置监听器

<!--配置spring监听器,默认只加载WEB-INF目录下面的spring.xml的配置文件-->
<listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--所以就设置配置文件的路径,表示加载的是类路径下面的配置文件,spring-config和spring-mvc两个配置文件都加载了,
    那么service和controller也就都加进容器中了,此时就可以进行依赖注入-->
<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath:spring-config.xml</param-value>
</context-param>

2.在控制器中注入service,调用其方法

private AccountService accountService;

@Autowired
public void setAccountService(AccountService accountService) {
    this.accountService = accountService;
}
accountService.findAll();

五.mybatis框架的搭建

1.直接在dao上加sql注解

@Select("select * from account")
public List<Account> findAll();

@Insert("insert into account(name,money) values(#{name},#{money})")
public void saveAccount(Account account);

2.搭建mybati环境

1.编写SqlMapConfig.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>
    <environments default="mysql">
        <environment id="mysql">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <!--配置数据库参数-->
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/ssm"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>

    <!--引入配置文件,用package可以扫描该包下的所有类-->
    <mappers>
        <package name="cn.tf.dao"/>
    </mappers>

</configuration>

2.测试mybatis环境

public class TestMyBatis {

    /**
     * 测试查询所有的账户信息
     * @throws Exception
     */
    @Test
    public void run1() throws Exception{
        //1.加载配置文件
        InputStream is= Resources.getResourceAsStream("SqlMapConfig.xml");
        //2.创建SqlSessionFactory工厂
        SqlSessionFactory  factory=new SqlSessionFactoryBuilder().build(is);
        //3.使用工厂创建SqlSession对象
        SqlSession session=factory.openSession();
        //4.因为dao没有实现类,所以获取其代理对象dao
        AccountDao dao = session.getMapper(AccountDao.class);
        //5.这样就可以用它的方法了
        List<Account> list = dao.findAll();
        for(Account account:list){
            System.out.println(account);
        }
        //6.关闭资源
        session.close();
        is.close();
    }
}

    /**
     * 测试插入账户信息
     * @throws Exception
     */
    @Test
    public void run2() throws Exception{
        Account account=new Account();
        account.setName("滕飞88");
        account.setMoney(12534d);
        //1.加载配置文件
        InputStream is= Resources.getResourceAsStream("SqlMapConfig.xml");
        //2.创建SqlSessionFactory工厂
        SqlSessionFactory  factory=new SqlSessionFactoryBuilder().build(is);
        //3.使用工厂创建SqlSession对象
        SqlSession session=factory.openSession();
        //4.因为dao没有实现类,所以获取其代理对象dao
        AccountDao dao = session.getMapper(AccountDao.class);
        //5.这样就可以用它的方法了
        dao.saveAccount(account);

        //提交事务
        session.commit();

        //6.关闭资源
        session.close();
        is.close();
    }

六.spring整合mybatis

service已经放进了ioc容器,所以dao放进service就相当于放进了dao也放进了ioc容器,又dao没有实现类,所以就放他的代理对象存进ioc容器。

1.配置spring.xml的mybatis内容

<!--spring整合mybatis,即把mybatis里面的配置内容放进spring中,让spring来创建代理,并存入IOC的容器中-->
<!--配置连接池-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
    <property name="jdbcUrl" value="jb=dbc:mysql:///ssm"></property>
    <property name="user" value="root"></property>
    <property name="password" value="1234"></property>
</bean>

<!--配置SqlSessionFactory工厂对象
    有了工厂就可以创建SqlSession,有了SqlSession就可以拿到代理对象,有了代理就可以把代理存到ioc容器
    通过连接池就可以构建sqlSessionFactory这个工厂,ref是引入上面dataSource对象-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource"></property>
</bean>

<!--配置AccountDao接口所在的包,即生成接口的代理对象,MapperScannerConfigurer映射扫描配置的类-->
<bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="cn.tf.dao"></property>  <!--要扫描的是cn.tf.Dao下面的包-->
</bean>

2.在dao上加注解,把dao也交给ioc去管理

@Repository
public interface AccountDao {
}

3.在AccountServiceImpl里面注入AccoutDao

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

    private AccountDao accountDao;

    /**
     * 把accountDao注进service,这样就可以调用accountDao里面的方法
     */
    @Autowired
    public void setAccountDao(AccountDao accountDao) {
        this.accountDao = accountDao;
    }

    @Override
    public List<Account> findAll() {
        System.out.println("业务层:查询了所有账户...");
        return accountDao.findAll();//使用注入的方法
    }
}

4.调用controller,用里面的service方法

@Controller
@RequestMapping("account")  //设置一级请求目录
public class AccountController {

    private AccountService accountService;

    @Autowired
    public void setAccountService(AccountService accountService) {
        this.accountService = accountService;
    }

    @RequestMapping("/findAll")   //设置二级请求目录
    public String findAll(Model model){
        System.out.println("表现层:查询所有执行了.....");
        List<Account> list=accountService.findAll();
        model.addAttribute("list",list);//用model存起来
        return "list";   //返回list,这是根据视图解析器来解析WEB-INF/pages下面的.jsp文件
    }
}

5.遍历mode存起来的数据

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
       <h3>恭喜,查询成功!</h3>

       <c:forEach items="${list}" var="account">
           ${account.name}
       </c:forEach>
</body>
</html>

6.最后输出

7.补漏:声明式事务管理(在spring.xml中配置事务)

1.配置spring框架声明式事务管理

<!--配置spring框架声明式事务管理-->
<!--配置事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"></property>
</bean>
<!--配置事务通知,这里的id值时下面AOP增强要引用的id,然后要引入上面的事务管理器,底层是提交、回滚等事务-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
    <tx:attributes>
        <tx:method name="find*" read-only="true"/><!--以find打头的方法设置为只读-->
    </tx:attributes>
</tx:advice>
<!--配置AOP增强,用advice-ref引用事务的通知,pointcut是切入点的表达式-->
<aop:config>
    <aop:advisor advice-ref="txAdvice" pointcut="execution(* cn.tf.service.impl.*ServiceImpl.*(..))"></aop:advisor>
</aop:config>

2.然后在前端编写代码

<a>测试保存</a><br>

  <form action="account/save" method="post">
      姓名:<input type="text" name="name"><br>
      金额:<input type="text" name="money"><br>
      <input type="submit" value="提交"><br>
  </form>

3.在controller里面写方法

/**
 * 保存的方法
 * @return
 */
@RequestMapping("/save")   //设置二级请求目录
public void save(Account account, HttpServletRequest request, HttpServletResponse response){ //前端(index.jsp)里面的数据封装到javaBean里面,所以这里传一个对象,就可以自动进行封装,              然后直接调用service里面的保存方法久可以了
    accountService.saveAccount(account);//调用service方法,然后service调用dao,而dao上面的                                               insert注解把数据保存进数据库
    //保存完事之后,选择个重定向,用上面的查询方法来进行查询 
    response.sendRedirect(request.getContextPath()+"/account/findAll");
    return ;   
}

本文链接http://smartadmin.com.cn/smartadmin/show-9233.html