再下一城 - SpringMVC框架笔记(三) SSM整合

文章目录

  • SpringMVC第三天
    • 第一章:搭建整合环境
      • 1. 搭建整合环境
    • 第二章:Spring框架代码的编写
      • 1. 搭建和测试Spring的开发环境
    • 第三章:Spring整合SpringMVC框架
      • 1. 搭建和测试SpringMVC的开发环境
      • 2. Spring整合SpringMVC的框架
    • 第四章:Spring整合MyBatis框架
      • 1. 搭建和测试MyBatis的环境
      • 2. Spring整合MyBatis框架

SpringMVC第三天


第一章:搭建整合环境

1. 搭建整合环境

  1. 整合说明:SSM整合可以使用多种方式,咱们会选择XML + 注解的方式

  2. 整合的思路

    1. 先搭建整合的环境
      1. 先把每个框架都测试一下,都没有问题,再进行整合
      2. 整合的方向:Spring整合SpringMVC,Spring整合Mybatis
    2. 先把Spring的配置搭建完成
    3. 再使用Spring整合SpringMVC框架
    4. 最后使用Spring整合MyBatis框架

  1. 创建数据库和表结构

        CREATE DATABASE ssm;
        USE ssm;
        CREATE TABLE account(
            id INT PRIMARY KEY AUTO_INCREMENT,
            NAME VARCHAR(20),
            money DOUBLE
        );
    
  2. 创建maven工程:ssm,导入坐标依赖

      <dependencies>
        
        <dependency>
          <groupId>org.aspectjgroupId>
          <artifactId>aspectjweaverartifactId>
          <version>1.6.8version>
        dependency>
        <dependency>
          <groupId>org.springframeworkgroupId>
          <artifactId>spring-aopartifactId>
          <version>${spring.version}version>
        dependency>
        <dependency>
          <groupId>org.springframeworkgroupId>
          <artifactId>spring-contextartifactId>
          <version>${spring.version}version>
        dependency>
        <dependency>
          <groupId>org.springframeworkgroupId>
          <artifactId>spring-webartifactId>
          <version>${spring.version}version>
        dependency>
        <dependency>
          <groupId>org.springframeworkgroupId>
          <artifactId>spring-webmvcartifactId>
          <version>${spring.version}version>
        dependency>
        <dependency>
          <groupId>org.springframeworkgroupId>
          <artifactId>spring-testartifactId>
          <version>${spring.version}version>
        dependency>
        <dependency>
          <groupId>org.springframeworkgroupId>
          <artifactId>spring-txartifactId>
          <version>${spring.version}version>
        dependency>
        <dependency>
          <groupId>org.springframeworkgroupId>
          <artifactId>spring-jdbcartifactId>
          <version>${spring.version}version>
        dependency>
        <dependency>
          <groupId>junitgroupId>
          <artifactId>junitartifactId>
          <version>4.12version>
          <scope>compilescope>
        dependency>
        <dependency>
          <groupId>mysqlgroupId>
          <artifactId>mysql-connector-javaartifactId>
          <version>${mysql.version}version>
        dependency>
        <dependency>
          <groupId>javax.servletgroupId>
          <artifactId>servlet-apiartifactId>
          <version>2.5version>
          <scope>providedscope>
        dependency>
        <dependency>
          <groupId>javax.servlet.jspgroupId>
          <artifactId>jsp-apiartifactId>
          <version>2.0version>
          <scope>providedscope>
        dependency>
        <dependency>
          <groupId>jstlgroupId>
          <artifactId>jstlartifactId>
          <version>1.2version>
        dependency>
        
        <dependency>
          <groupId>log4jgroupId>
          <artifactId>log4jartifactId>
          <version>${log4j.version}version>
        dependency>
        <dependency>
          <groupId>org.slf4jgroupId>
          <artifactId>slf4j-apiartifactId>
          <version>${slf4j.version}version>
        dependency>
        <dependency>
          <groupId>org.slf4jgroupId>
          <artifactId>slf4j-log4j12artifactId>
          <version>${slf4j.version}version>
        dependency>
        
        <dependency>
          <groupId>org.mybatisgroupId>
          <artifactId>mybatisartifactId>
          <version>${mybatis.version}version>
        dependency>
    
        <dependency>
          <groupId>org.mybatisgroupId>
          <artifactId>mybatis-springartifactId>
          <version>1.3.0version>
        dependency>
        <dependency>
          <groupId>c3p0groupId>
          <artifactId>c3p0artifactId>
          <version>0.9.1.2version>
          <type>jartype>
          <scope>compilescope>
        dependency>
      dependencies>
    
  3. 部署项目

  4. 编写实体类、dao接口、service接口和实现类


第二章:Spring框架代码的编写

1. 搭建和测试Spring的开发环境

  1. 创建applicationContext.xml的配置文件

    
    <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">
    
        
        <context:component-scan base-package="cn.itcast">
            
            <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
        context:component-scan>
    beans>
    
  2. 编写测试方法

        @Test
        public void test1(){
           
            //加载配置文件
            ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
            //获取对象
            IAccountService as = (IAccountService) ac.getBean("accountService");
            //执行方法
            as.findAll();
        }
    

第三章:Spring整合SpringMVC框架

1. 搭建和测试SpringMVC的开发环境

  1. 在web.xml中配置DispatcherServlet前端控制器,以及解决中文乱码的过滤器

      
      <servlet>
        <servlet-name>dispatcherServletservlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
        
        <init-param>
          <param-name>contextConfigLocationparam-name>
          <param-value>classpath:springmvc.xmlparam-value>
        init-param>
        
        <load-on-startup>1load-on-startup>
      servlet>
      <servlet-mapping>
        <servlet-name>dispatcherServletservlet-name>
        <url-pattern>/url-pattern>
      servlet-mapping>
    
    
      
      <filter>
        <filter-name>characterEncodingFilterfilter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
        <init-param>
          <param-name>encodingparam-name>
          <param-value>UTF-8param-value>
        init-param>
      filter>
      <filter-mapping>
        <filter-name>characterEncodingFilterfilter-name>
        <url-pattern>/*url-pattern>
      filter-mapping>
    
  2. 创建springmvc.xml的配置文件

    
    <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">
    
        
        <context:component-scan base-package="cn.itcast">
            
            <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
        context:component-scan>
    
        
        <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>
    
        
        <mvc:resources mapping="/css/**" location="/css">mvc:resources>
        <mvc:resources mapping="/images/**" location="/images">mvc:resources>
        <mvc:resources mapping="/js/**" location="/js">mvc:resources>
    
        
        <mvc:annotation-driven>mvc:annotation-driven>
    beans>
    
  3. 测试SpringMVC的框架搭建是否成功

    1. 编写JSP页面

      1. index.jsp
      2. list.jsp(成功跳转页面)
    2. 创建AccountController类,编写方法,进行测试

2. Spring整合SpringMVC的框架

  1. 目的:在controller中能成功的调用service对象中的方法。

  2. 在项目启动的时候,就去加载applicationContext.xml的配置文件(Spring的配置文件)

在web.xml中配置ContextLoaderListener监听器(该监听器默认只能加载WEB-INF目录下的applicationContext.xml的配置文件)。

  
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
  listener>
  
  <context-param>
    <param-name>contextConfigLocationparam-name>
    <param-value>classpath:applicationContext.xmlparam-value>
  context-param>
  1. 在controller中注入service对象,调用service对象的方法进行测试

    package cn.itcast.controller;
    
    import cn.itcast.service.IAccountService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    /**
     * 账户Web层
     */
    @Controller
    @RequestMapping("/account")
    public class AccountController {
           
    
        @Autowired
        private IAccountService accountService;
    
        /**
         * 查询所有
         * @return
         */
        @RequestMapping("/findAll")
        public String findAll(){
           
            System.out.println("表现层:查询所有账户....");
            accountService.findAll();
            return "list";
        }
    }
    

第四章:Spring整合MyBatis框架

1. 搭建和测试MyBatis的环境

  1. 在web项目中编写SqlMapConfig.xml的配置文件,编写核心配置文件

    
    
    
    <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:///ssm"/>
                    <property name="username" value="root"/>
                    <property name="password" value="root"/>
                dataSource>
            environment>
        environments>
    
        
        <mappers>
            <package name="cn.itcast.dao"/>
        mappers>
    configuration>
    
  2. 在AccountDao接口的方法上添加注解,编写SQL语句

    package cn.itcast.dao;
    
    import cn.itcast.domain.Account;
    import org.apache.ibatis.annotations.Insert;
    import org.apache.ibatis.annotations.Select;
    
    import java.util.List;
    
    /**
     * 账户持久层接口
     * Mybatis中,持久层接口不需要写实现类。通过代理dao的方式实现
     */
    public interface IAccountDao {
           
    
        /**
         * 查询所有账户
         * @return
         */
        @Select("select * from account")
        List<Account> findAll();
    
        /**
         * 保存账户
         * @param account
         */
        @Insert("insert into account (name,money) values(#{name},#{money})")
        void saveAccount(Account account);
    
    }
    
  3. 编写测试的方法

    package cn.itcast.test;
    
    import cn.itcast.dao.IAccountDao;
    import cn.itcast.domain.Account;
    import org.apache.ibatis.io.Resources;
    import org.apache.ibatis.session.SqlSession;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.apache.ibatis.session.SqlSessionFactoryBuilder;
    import org.junit.After;
    import org.junit.Before;
    import org.junit.Test;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.List;
    
    /**
     * 测试Mybatis框架是否可用
     */
    public class TestMybatis {
           
    
        private InputStream in;
        private SqlSession sqlSession;
        private IAccountDao accountDao;
    
        /**
         * 执行测试方法之前,初始化
         */
        @Before
        public void init() throws Exception {
           
            //加载配置文件
            in = Resources.getResourceAsStream("SqlMapConfig.xml");
            //创建SqlSessionFactory工厂
            SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
            //创建SqlSession对象
            sqlSession = factory.openSession();
            //获取dao的代理对象
            accountDao = sqlSession.getMapper(IAccountDao.class);
        }
    
    
        /**
         * 执行测试方法之后,释放资源
         */
        @After
        public void destroy() throws Exception {
           
            //执行增删改操作,需要手动提交事务
            sqlSession.commit();
            //关闭资源
            sqlSession.close();
            in.close();
        }
    
    
        /**
         * 测试查询所有
         * @throws Exception
         */
        @Test
        public void testFindAll() throws Exception {
           
            //查询所有
            List<Account> accounts = accountDao.findAll();
            //遍历
            for (Account account : accounts) {
           
                System.out.println(account);
            }
    
        }
    
    
        /**
         * 测试保存账户
         */
        @Test
        public void testSaveAccount(){
           
            Account account = new Account();
            account.setName("熊大");
            account.setMoney(2000.0);
            //保存账户
            accountDao.saveAccount(account);
        }
    }
    

2. Spring整合MyBatis框架

  1. 目的:把SqlMapConfig.xml配置文件中的内容配置到applicationContext.xml配置文件中

        
        <context:property-placeholder location="classpath:jdbcConfig.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>
        
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource">property>
        bean>
        
        <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <property name="basePackage" value="cn.itcast.dao">property>
        bean>
    
  2. 在AccountDao接口中添加@Repository注解

  3. 在service中注入dao对象。代码如下

    package cn.itcast.service.impl;
    
    import cn.itcast.dao.IAccountDao;
    import cn.itcast.domain.Account;
    import cn.itcast.service.IAccountService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import java.util.List;
    
    /**
     * 账户业务层实现类
     */
    @Service("accountService")
    public class AccountServiceImpl implements IAccountService {
           
    
        @Autowired
        private IAccountDao accountDao;
    
        @Override
        public List<Account> findAll() {
           
            System.out.println("业务层:查询所有账户....");
            return accountDao.findAll();
        }
    
        @Override
        public void saveAccount(Account account) {
           
            System.out.println("业务层:保存账户....");
            accountDao.saveAccount(account);
        }
    }
    
  4. 测试查询所有方法

    1. 控制器代码。

      package cn.itcast.controller;
      
      import cn.itcast.domain.Account;
      import cn.itcast.service.IAccountService;
      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;
      
      /**
       * 账户Web层
       */
      @Controller
      @RequestMapping("/account")
      public class AccountController {
               
      
          @Autowired
          private IAccountService accountService;
      
          /**
           * 查询所有
           * @return
           */
          @RequestMapping("/findAll")
          public String findAll(Model model){
               
              System.out.println("表现层:查询所有账户....");
              List<Account> list = accountService.findAll();
              model.addAttribute("list", list);
              return "list";
          }
      }
      
    2. 编写JSP页面

      <%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
      <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
      
      
      
          Title
      
      
          
          

      查询所有账户...

      ${account.name},${account.money}
  5. 配置Spring的声明式事务管理

        
        
        <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="find*" propagation="SUPPORTS" read-only="true"/>
                <tx:method name="*" propagation="REQUIRED" read-only="false">tx:method>
            tx:attributes>
        tx:advice>
        
        <aop:config>
            
            <aop:pointcut id="pt1" expression="execution(* cn.itcast.service.impl.*.*(..))"/>
            
            <aop:advisor advice-ref="txAdvice" pointcut-ref="pt1">aop:advisor>
        aop:config>
    
  6. 测试保存方法

    1. 编写JSP页面

          
      姓名:
      金额:
    2. 编写控制器

          /**
           * 保存
           * @return
           */
          @RequestMapping("/saveAccount")
          public void saveAccount(Account account, HttpServletRequest request, HttpServletResponse response) throws IOException {
               
              System.out.println("表现层:保存账户....");
              accountService.saveAccount(account);
              //重定向
              response.sendRedirect(request.getContextPath()+"/account/findAll");
          }
      
    3. 编写控制器

          /**
           * 保存
           * @return
           */
          @RequestMapping("/saveAccount")
          public void saveAccount(Account account, HttpServletRequest request, HttpServletResponse response) throws IOException {
               
              System.out.println("表现层:保存账户....");
              accountService.saveAccount(account);
              //重定向
              response.sendRedirect(request.getContextPath()+"/account/findAll");
          }
      

你可能感兴趣的:(SSM框架,java,spring,软件框架)