SSM整合

表现层:SpringMVC

业务层:Spring

持久层:Mybatis

用Spring框架整合其它两个框架。

搭建工程:

1.Maven选择webapp项目

2.不能有父工程

  1. 解决创建Maven创建过慢问题。

Name:archetypeCatalog Value:internal

1.idea 基本操作

idea中Mark Directory As里的Sources Root、ReSources Root等的区别:

1.1 source root

  1. 通过这个类指定一个文件夹,你告诉IntelliJ IDEA,这个文件夹及其子文件夹中包含的源代码,可以编译为构建过程的一部分。

1.2 test source roots

这些根类似于源根,但用于用于测试的代码(例如用于单元测试)。测试源文件夹允许您将与测试相关的代码与生产代码分开。

通常,源和测试源的编译结果被放置在不同的文件夹中。

1.3 resource roots

用于应用程序中的资源文件(图像、各种配置XML和属性文件等)。

在构建过程中,资源文件夹的所有内容都复制到输出文件夹中

1.4 test resource roots

是资源文件与您的测试源有关。在所有其他方面,这些文件夹类似于资源文件夹

2.开始整合

2.1 Maven :SSM整合所需环境

<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>
    <scope>compile</scope>
  </dependency>

  <!--mysql 驱动的jar包-->
  <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>

  <!--页面的el表达式,jstl库-->
  <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-->

  <!--数据库 start-->
  <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>${mybatis.version}</version>
  </dependency>

  <!--整合所需jar包-->
  <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>

2.2新建文件夹

2.2.1新建一个存放java源代码的文件夹(java)
将其设定为:source roots

2.2.2新建一个存放配置文件的文件夹
将其设定为:resource roots

2.2.3在java文件夹里新建包
在包里先创建好MVC三层目录。(Controller、service、dao)和pojo类。

3.搭建Spring环境并测试

因为是由Spring框架去整合其它两个框架,所以,首先搭建的是Spring的环境。

每搭建一个框架就先单独测试一下:这个框架是否可用。可用再整合。

3.1创建配置文件

Spring的配置文件负责扫描业务层(Spring)和持久层(Mybatis)的注解。

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:txs="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">

    <!--开启注解的扫描,spring 容器只处理service和dao(也就是业务层和持久层),不处理controller-->
    <context:component-scan base-package="cn.guolian">
        <!--配置哪些注解不扫描-->
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"></context:exclude-filter>
    </context:component-scan>

</beans>

3.2简单测试Spring框架

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

    @Override
    public void saveAcount(Account account) {
        System.out.println("业务层保存账户");
    }
}

3.2.2TestSpring
public class TestSpring {

    @Test
    public void test1() {
        //加载配置文件
        ApplicationContext ac
                = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
        //获取对象
        AccountService accountService =(AccountService) ac.getBean("accountService");
        //自动装配之后调用方法
        accountService.findAll();

    }
}

4.搭建SpringMVC环境并测试

4.1创建配置文件

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

    <!-- 扫描组件 -->
    <context:component-scan base-package="cn.guolian">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"></context:include-filter>
    </context:component-scan>

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

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

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

4.2简单测试Springmvc框架

4.2.1AccountController
/**
 * 账户web层
 */
@Controller
@RequestMapping("/account")
public class AccountController {
    @RequestMapping("/findAll")
    public String findAll(){
        System.out.println("表现层查询所有账户信息");
        return "list";
    }
}

4.2.2index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
        <a href="account/findAll">测试</a>
</body>
</html>

4.2.3list.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
        <h3>查询了所有的账户信息</h3>
</body>
</html>

5.整合Spring和SpringMVC

spring整合springmvc 成功的标志:

    通过在jsp页面点击,跳转到controller表现层,然后在表现层的方法里调用了service业务层的方法。

如果我们需要在表现层调用业务层的方法,就需要业务层的类的对象

需要业务层的类的对象,就需要加载spring的配置文件(依赖注入)

springmvc的配置文件在web容器加载时就已经加载了。而spring的容器在调用时才加载

所以我们需要提前加载spring的配置文件。(在servletcontextlistener 的监听器里去加载)

5.1在web.xml里配置监听器加载spring

  <!--设置配置文件的路径
      让监听器去加载类路径下的applicationContext.xml-->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>

<!--配置Spring的监听器,默认只加载WEB-INF目录下的applicationContext.xml
    可以通过 context-param 标签配置加载路径-->
<listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

5.2在表现层方法里调用业务层方法

通过依赖注入。

5.2.1AccountController.java
/**
 * 账户web层
 */
@Controller
@RequestMapping("/account")
public class AccountController {

    @Autowired
    private AccountService accountService;

    @RequestMapping("/findAll")
    public String findAll(){
        System.out.println("表现层查询所有账户信息");
        accountService.findAll();
        return "list";
    }
}

6.搭建MyBatis环境并测试

6.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>

    <!--进入资源文件-->
    <properties resource="jdbc.properties"></properties>

    <!--配置环境-->
    <environments default="mysql">
        <environment id="mysql">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>

    <!--引入映射文件-->
    <mappers>
        <package name="cn.guolian.dao" />
    </mappers>
</configuration>

6.2映射配置文件

如果用注解的方式写SQL语句,则不用映射文件。

<!--Emp getEmpByEid(String eid);-->
<select id="getEmpByEid" resultType="com.guolian.bean.Emp">
    SELECT * FROM emp WHERE eid = #{eid}
</select>

<!--Integer getCount();-->
<select id="getCount" resultType="Integer">
    SELECT COUNT(eid) FROM emp
</select>

<!-- Map<String,Object> getEmpMapByEid(String eid);-->
<!--将单条查询信息放入Map集合中,以字段名为键以字段值为值-->
<select id="getEmpMapByEid" resultType="hashmap">
    SELECT * FROM emp WHERE eid = #{eid}
</select>

<!--Map<String,Object> getAllEmpMap();-->
<!--将多条查询信息放入Map集合中,需要在接口的方法上加上注解@MapKey("")。为Map集合设置键-->
<select id="getAllEmpMap" resultType="hashmap">
    SELECT * FROM emp
</select>

6.3注释的方式写SQL语句

6.3.1AccountDao.java:
/**
 * 账户Dao接口
 */
public interface AccountDao {

    //查询所有账户
    @Select("select * from account")
    public List<Account> findAll();
    //保存账户信息
    @Insert("insert into account(name,money) values (#{name},#{money})")
    public void saveAcount(Account account);
}

6.4简单测试

public class TestMyBatis {

    @Test
    public void run1() throws IOException {
        //加载Mybatis的配置文件
        InputStream resourceAsStream
                = Resources.getResourceAsStream("SqlMapConfig.xml");

        //创建SqlSessionFactory对象
        SqlSessionFactory build
                = new SqlSessionFactoryBuilder().build(resourceAsStream);

        //创建Sqlsession对象,true:自动提交事务
        SqlSession sqlSession = build.openSession(true);

        //获取代理对象
        AccountDao mapper = sqlSession.getMapper(AccountDao.class);

        //查询所有账户信息
        List<Account> list = mapper.findAll();
        for (Account account:list){
            System.out.println(account);
        }

        //关闭资源
        sqlSession.close();
        resourceAsStream.close();
    }
}

7.整合Spring和MyBatis

将Dao层的代理对象都交给Spring的IOC容器管理。这样,业务层(Service)就可以使用依赖注入的方法直接调用Dao层的方法。

7.1在Spring配置文件中配置

7.1.1applicationContext.xml:

将MyBatis的核心配置文件里的内容写到Spring配置文件中。

在Spring配置文件中,配置SqlSessionFactory工厂和接口所在包,这样它就可以自动的为我们创建对应的SqlSession对象并获取对应接口类的代理对象。

<!--Spring整合MyBatis框架-->
<!--配置连接池-->
<!--引入外部文件,ignore-resource-not-found:如果找不到文件是否将其忽略,false:忽略。-->
<context:property-placeholder ignore-resource-not-found="false" location="classpath:jdbc.properties"></context:property-placeholder>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <property name="driverClass" value="${jdbc.driver}"></property>
    <property name="jdbcUrl" value="${jdbc.url}"></property>
    <property name="user" value="${jdbc.username}"></property>
    <property name="password" value="${jdbc.password}"></property>
</bean>

<!--配置SqlSessionFactory工厂-->
<bean id="SqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource"></property>
</bean>

<!--配置AccountDao接口所在包-->
<bean id="mapperscanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
     <property name="basePackage" value="cn.guolian.dao"></property>
</bean>

7.2在service层中依赖注入Dao层方法

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

    @Autowired
    private AccountDao accountDao;

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

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