SSM的整合

目录

一、整合分析

整合的示例:

整合的配置方式:

整合步骤分析:

二、SSM整合

1.建表

2.创建表对应的实体对象

3.创建Service层的java类

4.搭建Spring环境

(1)导入Spring的pom坐标

(2)Spring的配置文件

(3)测试Spring能否独立运行

5.搭建MyBatis环境

(1)导入MyBatis的pom依赖

(2)MyBatis的配置文件

(3)编写Account对应的Dao层

(4)测试MyBatis能否独立运行

6.整合Spring和MyBatis

(1)导入整合的pom依赖

(2)Spring接管MyBatis

(3)改造Service

7.Junit测试整合结果

(1)导入pom依赖

(2)测试整合结果

8.搭建SpringMVC环境

(1)导入Spring的pom依赖

(2)配置web.xml

(3)配置springmvc.xml

(4)编写AccountController

(5)编写测试页面

(6)开启tomcat测试

9.整合Spring和SpringMVC

(1)配置web.xml

(2)改造AccountController


一、整合分析

整合的示例:

Account的保存和列表查询

整合的配置方式:

Mybatis:XML+注解的方式(最终只有注解)
Spring:XML+注解的方式(我们自己写的类用注解,别人写的用XML)
SpringMVC:XML+注解的方式(和spring的配置思想是一样的)

整合步骤分析:

第一步:保证spring框架可以在maven工程中独立运行(Spring的IOC环境搭建)           
第二步:保证mybatis框架可以在maven工程中独立运行(Mybatis的环境搭建)            
第三步:整合spring和mybatis                            
    思路:
       让spring接管SqlSessionFactory的创建
       以及spring接管代理dao实现类的创建
第四步:通过整合Junit测试spring和mybatis的整合结果                  
第五步:保证springmvc框架可以在maven工程中独立运行(SpringMVC环境搭建)         
第六步:整合spring和springmv,把service对象注入到controller中

二、SSM整合

1.建表

create table account(
	id int primary key auto_increment,
	name varchar(40),
	money float
)character set utf8 collate utf8_general_ci;

insert into account(name,money) values('aaa',1000);
insert into account(name,money) values('bbb',1000);
insert into account(name,money) values('ccc',1000);

2.创建表对应的实体对象

public class Account {
    private Integer id;
    private String name;
    private Float money;
}

3.创建Service层的java类

public interface IAccountService {
    /**
     * 保存账户
     *
     * @param account
     */
    void saveAccount(Account account);
​
    /**
     * 查询所有账户
     *
     * @return
     */
    List<Account> findAllAccount();
}
@Service("accountService")
public class AccountServiceImpl implements IAccountService {
​
    @Override
    public void saveAccount(Account account) {
        System.out.println("savaAccount方法执行了");
    }
​
    @Override
    public List<Account> findAllAccount() {
        System.out.println("findAllAccount方法执行了");
        return null;
    }
}

4.搭建Spring环境

(1)导入Spring的pom坐标

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.4.RELEASE</version>
        </dependency>

(2)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" xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx" 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/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
​
    <!-- 配置spring创建容器时要扫描的包 -->
    <context:component-scan base-package="com.itheima">
        <!--制定扫包规则,不扫描@Controller注解的JAVA类,其他的还是要扫描 -->
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
  
</beans>

(3)测试Spring能否独立运行

public class Test01Spring {
    public static void main(String[] args) {
        ApplicationContext applicationContext=
                new ClassPathXmlApplicationContext("applicationContext.xml");
        IAccountService accountService = applicationContext.getBean("accountService", IAccountService.class);
        accountService.findAllAccount();
        accountService.saveAccount(new Account());
    }
}
打印
结果如下:
findAllAccount方法执行了
savaAccount方法执行了

5.搭建MyBatis环境

(1)导入MyBatis的pom依赖

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.5</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
        <!-- 此次整合用druid的连接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.9</version>
        </dependency>

(2)MyBatis的配置文件

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来引入外部properties配置文件的内容-->
    <properties resource="jdbcConfig.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>
        <!-- 自动扫描指定包下的Dao -->
        <package name="com.itheima.dao"/>
    </mappers>
</configuration>

druid.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/ssm
jdbc.username=root
jdbc.password=123456

(3)编写Account对应的Dao层

AccountDao.java

@Repository
public interface AccountDao {
    /**
     * 保存
     *
     * @param account
     */
    void save(Account account);
​
    /**
     * 查询所有
     *
     * @return
     */
    List<Account> findAll();
}

AccountDao.xml

<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.itheima.dao.AccountDao">
    <!-- 查询所有账户 -->
    <select id="findAll" resultType="com.itheima.domain.Account">
        select * from account
    </select>
    <!-- 新增账户 -->
    <insert id="save" parameterType="com.itheima.domain.Account">
        insert into account(name,money)
        values(#{name},#{money})
    </insert>
</mapper>

(4)测试MyBatis能否独立运行

public class Test01MyBatis {
    private static SqlSessionFactory getSqlSessionFactory() throws IOException {
        //1.根据xml配置文件创建一个SqlSessionFactory对象
        String resource = "conf/mybatis-config.xml";
        InputStream resourceAsStream = Resources.getResourceAsStream(resource);
        return new SqlSessionFactoryBuilder().build(resourceAsStream);
    }
    @Test
    public void test01() throws Exception {
        //1.获取SqlSessionFactory
        SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
        //2.获取sqlSession对象
        SqlSession session = sqlSessionFactory.openSession();
        //3.获取接口的实现类对象
        AccountDao aDao = session.getMapper(AccountDao.class);
        Account account = new Account();
      
        //4.测试保存方法
        account.setName("test");
        account.setMoney(5000f);
        aDao.save(account);
      
        //5.测试查询方法
        List<Account> list = aDao.findAll();
        System.out.println(list);
        session.commit();
        session.close();
        in.close();
    }

6.整合Spring和MyBatis

(1)导入整合的pom依赖

        <!--导入spring和mybatis整合的坐标-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.0.4.RELEASE</version>
        </dependency>
​
        <!--配置aspectJ语言的解析坐标-->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.13</version>
        </dependency>

(2)Spring接管MyBatis

  • SqlMapConfig.xml配置文件中的东西可以删除,在Spring配置文件中配置

  • 以后也可以在SqlMapConfig.xml配置文件中进行某些配置,和Spring的配置文件共同生效

applicationContext.xml

    <!-- 加载配置文件 -->
    <context:property-placeholder location="classpath:druid.properties"/>
    <!-- 配置MyBatis的Session工厂 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 数据库连接池 -->
        <property name="dataSource" ref="dataSource"/>
        <!-- 加载mybatis的全局配置文件 -->
        <property name="configLocation" value="classpath:SqlMapConfig.xml"/>
    </bean>
    <!-- 配置数据源 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driver}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>
​
​
    <!-- 配置Mapper扫描器 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.itheima.dao"></property>
    </bean>
​
    <!-- 配置事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!-- 配置事务的通知 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="*" propagation="REQUIRED" read-only="false"/>
            <tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
        </tx:attributes>
    </tx:advice>
    <!-- 配置aop -->
    <aop:config>
        <!-- 配置切入点表达式 -->
        <aop:pointcut expression="execution(* com.itheima.service.impl.*.*(..))" id="pt1"/>
        <!-- 建立通知和切入点表达式的关系 -->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"/>
    </aop:config>

(3)改造Service

@Service("accountService")
public class AccountServiceImpl implements IAccountService {
    
    //将acountDao注入到AccountServiceImpl中
    @Autowired
    AccountDao accountDao;
​
    @Override
    public void saveAccount(Account account) {
        accountDao.save(account);
    }
​
    @Override
    public List<Account> findAllAccount() {
        List<Account> accounts = accountDao.findAll();
        return accounts;
    }
}

7.Junit测试整合结果

(1)导入pom依赖

        <!--导入spring和Junit的整合坐标-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.0.4.RELEASE</version>
        </dependency>

(2)测试整合结果

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
public class TestSpringMyBatis {
    @Autowired
    private IAccountService accountService;
​
    @Test
    public void testFindAll() {
        List list = accountService.findAllAccount();
        System.out.println(list);
    }
​
    @Test
    public void testSave() {
        Account account = new Account();
        account.setName("测试账号");
        account.setMoney(1234f);
        accountService.saveAccount(account);
    }
}

8.搭建SpringMVC环境

(1)导入Spring的pom依赖

        <!--导入springmvc和servlet api的坐标-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.0.4.RELEASE</version>
        </dependency>
        <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.0</version>
        </dependency>

(2)配置web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         version="2.5">
    <display-name>ssm_web</display-name>
    <!-- 配置spring mvc的核心控制器 -->
    <servlet>
        <servlet-name>springmvcDispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <!-- 配置初始化参数,用于读取springmvc的配置文件 -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
        <!-- 配置servlet的对象的创建时间点:应用加载时创建。取值只能是非0正整数,表示启动顺序 -->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvcDispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <!-- 配置springMVC编码过滤器 -->
    <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>
        <!-- 启动过滤器 -->
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <!-- 过滤所有请求 -->
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
  
</web-app>

(3)配置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">
​
    <!-- 配置创建spring容器要扫描的包 -->
    <context:component-scan base-package="com.itheima.controller">
    </context:component-scan>
​
    <!-- 配置视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
​
    <!-- 开启springmvc对注解的支持 -->
    <mvc:annotation-driven></mvc:annotation-driven>
</beans>

(4)编写AccountController

@Controller
@RequestMapping("account")
public class AccountController {
​
    @RequestMapping("findAllAccount")
    public String findAllAccount(){
        System.out.println("执行了查询账号");
        return "success";
    }
}
​

(5)编写测试页面

find.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>主页</title></head>
<body><a href="account/findAllAccount">访问查询账户</a></body>
</html>

(6)开启tomcat测试

  • 访问该页面后控制台打出以下信息:

执行了查询账号
  • 同时页面跳转到WEB-INF/pages下的success.jsp页面

9.整合Spring和SpringMVC

(1)配置web.xml

    <!-- 配置spring提供的监听器,用于启动服务时加载容器 -->
    <!-- 该监听器只能加载WEB-INF目录中名称为applicationContext.xml的配置文件 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!-- 手动指定spring配置文件位置 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>

(2)改造AccountController

@Controller
@RequestMapping("account")
public class AccountController {
​
    //把accountService对象注入进来
    @Autowired
    IAccountService accountService;
​
    @RequestMapping("findAllAccount")
    public String findAllAccount(){
        List<Account> accounts = accountService.findAllAccount();
        for (Account account : accounts) {
            System.out.println(account);
        }
        return "success";
    }
}

猜你喜欢

转载自blog.csdn.net/fy_java1995/article/details/84167655