SpringMVC_v15_ssm整合

整合目标 : 简单表单提交, 存至数据库.

对应代码仓库: https://github.com/yydcyy01/spring_v1/tree/master/SSM

01.说明

配置文件 / 注解 : 怎么简单怎么来. 今天演示陪住文件 + 注解

image-20191008183823721

整合过程 : 首先保证 SpringMVC / Spring / MyBatis 单独都是可用的. 然后再以 Spring 整合 左 / 右;

02.搭建环境

建工程, 模块 去除父工程.

三层目录结构 : dao / service / controller

image-20191008200613001

建数据库, 由表 创建 domain,java Bean => 配置pom.xml 文件=> service 层中 AccountService.java (AccountServiceImpl.java) => AccountDao.java => 创建 AccountController.java

创建 applicationContext.xml => test.TestSpring.java

配置注解

AccountServiceImpl 加@Service

03编写Spring框架

Spring 配置文件 :

applicationContext.xml 添加注解@Service(…)

/**
 * @author YYDCYY
 * @create 2019-10-08
 */
@Service("accountService")
public class AccountService implements com.yydcyy.service.AccountService {
    @Autowired
    private AccountDao accountDao;

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

    @Override
    public void saveAccount(Account account) {
        System.out.println("业务层:保存账户");
    }
}
配置注解

Controller.AccountController.java

test.TestSpring.java.

测试 Spring 可用性

结果 Demo

image-20191009104117179

运行 test.TestSpring.java, ok, Spring 环境没问题

04.编写SpringMVC框架

web.xml 配置前端控制器, 乱码处理.

spring.mvc 配置

配置 tomcat测试 SpringMVC 环境

webapp 下添加pages/list.jsp 测试 (不添加 Demo 演示成功,最后跳转失败 404 )

演示 Demo

image-20191009103907053

image-20191009104016187

SpringMVC 环境没问题

05.Spring整合SpringMVC的框架

web.xml 中配置 “配置Spring的监听器” , "设置配置文件的路径"加载 applicationContext.xml.

  <!--配置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>
AccountController.java

既然加载了 Spring 配置文件, 可以用注解了. 添加 accountService 属性, 使用 DI ,测试 index.jsp 页面

@Controller
@RequestMapping("/account")
public class AccountController {
    @Autowired
    private AccountService accountService;

    @RequestMapping("/findAll")
    public String findAll(Model model){
        System.out.println("表现层:查询所有账户...");
        // 调用service的方法
        List<Account> list = accountService.findAll();
        model.addAttribute("list",list);
        return "list";
    }
  ......
结果 Demo

image-20191009111237158

image-20191009111246880

整合成功

06.编写MyBatis框架

accountDao = > xml 配置文件(sql 语句) => SQLMapConfig.xml 配置文件. …

可以注解方式, 直接方法上@注解. (就不需要写配置文件了.

)

AccountDao.java
/**
 * 账户接口, 不需要写实现类, 框架实现
 * @author YYDCYY
 * @create 2019-10-09
 */
public interface AccountDao {
    // 查询所有账户
    @Select("select * from account")
    public List<Account> findAll();

    // 保存帐户信息
    @Insert("insert into account (name,money) values (#{name},#{money})")
    public void saveAccount(Account account);
}
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"/>
                <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql:///ssm"/>
                <property name="username" value="root"/>
                <property name="password" value="123123"/>
            </dataSource>
            </environment>
        </environments>
    
        <mappers>
            <!-- 使用注解 -->
        <!-- <mapper class="com.yydcyy.dao.AccountDao"/> -->
        <!-- 该包下所有的dao接口都可以使用 -->
        <package name="com.yydcyy.dao"/>
    
            <!-- 引用配置文件 -->
            <!--<mapper resource="com/yydcyy/dao/xxx.xml"/>-->
        </mappers>
    </configuration>
test.TestMyBatis
/**
 * @author YYDCYY
 * @create 2019-10-09
 */
public class testMyBatis {
    /**
     * 测试查询
     * @throws Exception
     */
    @Test
    public void run1() throws Exception {
        // 加载配置文件
        InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
        // 创建SqlSessionFactory对象
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        // 创建SqlSession对象
        SqlSession session = factory.openSession();
        // 获取到代理对象
        AccountDao dao = session.getMapper(AccountDao.class);
        // 查询所有数据
        List<Account> list = dao.findAll();
        for(Account account : list){
            System.out.println(account);
        }
        // 关闭资源
        session.close();
        in.close();
    }
}
结果 Demo

image-20191009130709662

07.编写MyBatis框架测试保存的方法

testMyBatis.java
/**
 * 测试保存
 * @throws Exception
 */
@Test
public void run2() throws Exception {
    Account account = new Account();
    account.setName("羽扬");
    account.setMoney(99999d);

    // 加载配置文件
    InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
    // 创建SqlSessionFactory对象
    SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
    // 创建SqlSession对象
    SqlSession session = factory.openSession();
    // 获取到代理对象
    AccountDao dao = session.getMapper(AccountDao.class);

    // 保存
    dao.saveAccount(account);

    // 提交事务  不提交, 不会保存至数据库的
    session.commit();

    // 关闭资源
    session.close();
    in.close();
}
结果 Demo

image-20191009131254523

image-20191009131241119

08.Spring整合MyBatis框架

applicationContext 中添加数据库信息. 整合 MyBatis

SqlMapConfig.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">

    <!--开启注解的扫描,希望处理service和dao,controller不需要Spring框架去处理-->
    <context:component-scan base-package="com.yydcyy" >
        <!--配置哪些注解不扫描-->
        <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.jdbc.Driver"/>
        <property name="jdbcUrl" value="jdbc:mysql:///ssm"/>
        <property name="user" value="root"/>
        <property name="password" value="123123"/>
    </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="com.yydcyy.dao"/>
    </bean>
</beans>
AccountServletImpl

添加 accountDao 属性 -> 配置注解 -> 处理并返回结果

/**
 * @author YYDCYY
 * @create 2019-10-09
 */
@Service("accountService")
public class AccountServiceImpl implements AccountService {

     @Autowired
    private AccountDao accountDao;

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

    public void saveAccount(Account account) {
        System.out.println("业务层:保存帐户...");
        accountDao.saveAccount(account);
    }
}
AccountDao.java
@Repository
public interface AccountDao {
    // 查询所有账户
    @Select("select * from account")
    public List<Account> findAll();

    // 保存帐户信息
    @Insert("insert into account (name,money) values (#{name},#{money})")
    public void saveAccount(Account account);
}
删除 SqlMapConfig.xml

删除 resources 目录下SqlMapConfig.xml 文件 (添加至)applicationContext.xml 里了

list.jsp

测试成功, 结果返回 list.jsp 页面并打印 ( 记得打开 idElIgnored= “false” / 引入 el 表达式: prefix=“c” )

<%@ 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>
结果 Demo

image-20191009144952717

image-20191009145009254

09.Spring整合MyBatis框架配置事务

applicationContext.xml

配置 Spring 事务管理, 事务通知, AOP

.....
    <!--配置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(* com.yydcyy.service.impl.*ServiceImpl.*(..))"/>
    </aop:config>
.....
AccountController

save 方法, 接收 account 执行 Service.save方法. 并获取 request 转发至查询页面.(调用 AccountController.java 下的 findAll 方法)

@Controller
@RequestMapping("/account")
public class AccountController {
    @Autowired
    private AccountService accountService;
  .....
    /**
     * 保存
     * @return
     */
    @RequestMapping("/save")
    public void save(Account account, HttpServletRequest request, HttpServletResponse response) throws IOException {
        accountService.saveAccount(account);
        response.sendRedirect(request.getContextPath()+"/account/findAll");
        return;
    }
}
AccountDao
@Repository
public interface AccountDao {
    // 查询所有账户
    @Select("select * from account")
    public List<Account> findAll();

    // 保存帐户信息
    @Insert("insert into account (name,money) values (#{name},#{money})")
    public void saveAccount(Account account);
}
AccountServiceImp;
@Service("accountService")
public class AccountServiceImpl implements AccountService {

     @Autowired
    private AccountDao accountDao;
...
    public void saveAccount(Account account) {
        System.out.println("业务层:保存帐户...");
        accountDao.saveAccount(account);
    }
}

image-20191009150743635

ok, 至此整合成功

目录结构

image-20191009151959271

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值