SSM整合(spring+springMVC+mybatis)

SSM整合

什么是SSM

SSM整合(spring+springMVC+mybatis)_第1张图片

即Spring,SpringMVC,Mybatis三大框架整合在一起的技术。

整合的思路

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

整合步骤

  1. 创建一个Maven工程,导入需要的坐标依赖(版本和连接池因人而异)

    <dependencies>
        <dependency>
          <groupId>junitgroupId>
          <artifactId>junitartifactId>
          <version>4.12version>
          <scope>compilescope>
        dependency>
        
        <dependency>
          <groupId>mysqlgroupId>
          <artifactId>mysql-connector-javaartifactId>
          <version>8.0.18version>
        dependency>
    
        
        <dependency>
          <groupId>org.aspectjgroupId>
          <artifactId>aspectjweaverartifactId>
          <version>1.8.14version>
        dependency>
        <dependency>
          <groupId>org.springframeworkgroupId>
          <artifactId>spring-webmvcartifactId>
          <version>${spring.version}version>
        dependency>
        <dependency>
          <groupId>org.springframeworkgroupId>
          <artifactId>spring-webartifactId>
          <version>${spring.version}version>
        dependency>
        <dependency>
          <groupId>org.springframeworkgroupId>
          <artifactId>spring-contextartifactId>
          <version>${spring.version}version>
        dependency>
        <dependency>
          <groupId>org.springframeworkgroupId>
          <artifactId>spring-aopartifactId>
          <version>${spring.version}version>
        dependency>
        <dependency>
          <groupId>org.springframeworkgroupId>
          <artifactId>spring-jdbcartifactId>
          <version>${spring.version}version>
        dependency>
        <dependency>
          <groupId>org.springframeworkgroupId>
          <artifactId>spring-txartifactId>
          <version>${spring.version}version>
        dependency>
        <dependency>
          <groupId>org.springframeworkgroupId>
          <artifactId>spring-testartifactId>
          <version>5.1.5.RELEASEversion>
        dependency>
    
        
        <dependency>
          <groupId>javax.servlet.jspgroupId>
          <artifactId>javax.servlet.jsp-apiartifactId>
          <version>2.3.3version>
          <scope>providedscope>
        dependency>
        
        <dependency>
          <groupId>javax.servlet.jsp.jstlgroupId>
          <artifactId>jstlartifactId>
          <version>1.2version>
        dependency>
        <dependency>
          <groupId>taglibsgroupId>
          <artifactId>standardartifactId>
          <version>1.1.2version>
        dependency>
    
        
        <dependency>
          <groupId>org.mybatisgroupId>
          <artifactId>mybatisartifactId>
          <version>3.5.4version>
        dependency>
        <dependency>
          <groupId>org.mybatisgroupId>
          <artifactId>mybatis-springartifactId>
          <version>2.0.3version>
        dependency>
    
        
        <dependency>
          <groupId>log4jgroupId>
          <artifactId>log4jartifactId>
          <version>1.2.17version>
        dependency>
    
        <dependency>
          <groupId>org.slf4jgroupId>
          <artifactId>slf4j-log4j12artifactId>
          <version>1.7.30version>
    
        dependency>
        <dependency>
          <groupId>org.slf4jgroupId>
          <artifactId>slf4j-apiartifactId>
          <version>1.7.30version>
        dependency>
      
        <dependency>
          <groupId>com.alibabagroupId>
          <artifactId>druidartifactId>
          <version>1.1.21version>
        dependency>
        <dependency>
         
          <groupId>org.junit.jupitergroupId>
          <artifactId>junit-jupiterartifactId>
          <version>RELEASEversion>
          <scope>compilescope>
        dependency>
        <dependency>
          
          <groupId>javax.servletgroupId>
          <artifactId>javax.servlet-apiartifactId>
          <version>3.0.1version>
          <scope>providedscope>
        dependency>
      dependencies>
    
  2. 编写spring的配置文件

    
    <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:context="http://www.springframework.org/schema/context"
           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/aop
            https://www.springframework.org/schema/aop/spring-aop.xsd
            http://www.springframework.org/schema/context
            https://www.springframework.org/schema/context/spring-context.xsd
             http://www.springframework.org/schema/tx
            https://www.springframework.org/schema/tx/spring-tx.xsd"
    >
        
        <context:component-scan base-package="cn.okt">
            
            <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
        context:component-scan>
        beans>
    
  3. 编写java代码

    1. 业务层

      
      public interface AccountService {
          // 查询所有账户信息
          List<Account> findAll();
      
          // 保存账户信息
          void saveAccount(Account account);
      }
      
      
      @Service("accountService")
      public class AccountServiceImpl implements AccountService{
      
      
          public List<Account> findAll() {
              System.out.println("业务层:查询所有账户...");
              return null;
          }
      
          public void saveAccount(Account account) {
              System.out.println("业务层:保存帐户...");
          }
      }
      
    2. 持久层

      
      /**
       * 帐户dao接口
       */
      public interface AccountDao {
      
          // 查询所有账户
          public List<Account> findAll();
      
          // 保存帐户信息
          public void saveAccount(Account account);
      
      }
      
    3. 实体类

      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 +
                      '}';
          }
      }
      
  4. 编写测试类,测试spring环境是否搭建成功

    public class TestSpring {
        @Test
        public void run1(){
            ApplicationContext ac=new ClassPathXmlApplicationContext("classpath:spring的配置文件名称");
            AccountService service=(AccountService) ac.getBean("accountService");
            service.findAll();
            service.saveAccount(new Account());
        }
    }
    
  5. Spring整合springMVC,编写web.xml,配置前端控制器,中文乱码,Spring监听器

    
    <web-app>
        <display-name>Archetype Created Web Applicationdisplay-name>
        
        <listener>
            <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
        listener>
        
        <context-param>
            <param-name>contextConfigLocationparam-name>
            <param-value>classpath:spring配置名称param-value>
        context-param>
        
        <servlet>
            <servlet-name>dispatcherServletservlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
            
            <init-param>
                <param-name>contextConfigLocationparam-name>
                <param-value>classpath:springmvc配置名称param-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>
    
    web-app>
    
    
  6. 编写SpringMVC配置文件

    
        
        
            
        
        
        
            
            
        
    
        
    	
        
        
    
    
    
    
  7. 编写控制层代码

    /**
     * 帐户web
     */
    @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";
        }
    }
    
  8. 编写前端页面,并开启tomcat测试

    <index页面>
    
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>Titletitle>
    head>
    <body>
    <h3>测试h3>
    <a href="account/findAll">测试a>
        <form action="account/save" method="post">
            姓名:<input type="text" name="name"><br>
            金额:<input type="text" name="money"><br>
            <input type="submit" value="保存">
        form>
    body>
    html>
    
    
    
    <%@ page contentType="text/html;charset=UTF-8" language="java"  isELIgnored="false" %>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
    
    
        Title
    
    
        

    已成功查询

  9. Spring整合Mybatis,修改持久层和业务层代码

    @Service("accountService")
    public class AccountServiceImpl implements AccountService{
    
        @Autowired
        private AccountDao accountDao;
    
        public List<Account> findAll() {
            System.out.println("业务层:查询所有账户...");
            return accountDao.findAll();
        }
    
        public void saveAccount(Account account) {
            System.out.println("业务层:保存帐户...");
            accountDao.saveAccount(account);
        }
    }
    
    /**
     * 帐户dao接口
     */
    @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);
    
    }
    
  10. 在spring配置文件中配置mybatis

    
    <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:context="http://www.springframework.org/schema/context"
           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/aop
            https://www.springframework.org/schema/aop/spring-aop.xsd
            http://www.springframework.org/schema/context
            https://www.springframework.org/schema/context/spring-context.xsd
             http://www.springframework.org/schema/tx
            https://www.springframework.org/schema/tx/spring-tx.xsd"
    >
        
        <context:component-scan base-package="cn.okt">
            
            <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
        context:component-scan>
    
        
        
        <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
            <property name="driverClassName" value="com.mysql.cj.jdbc.Driver">property>
            <property name="url" value="jdbc:mysql:///ssm?serverTimezone=UTC">property>
            <property name="username" value="root">property>
            <property name="password" value="19970930">property>
        bean>
        
        <bean id="sessionFactory" 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.okt.dao">property>
        bean>
    beans>  
    
  11. 修改前端页面list.jsp,并打开Tomcat进行测试

    <%@ 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}
  12. Spring配置事务,在spring配置文件中添加如下

        
        <tx:advice id="txAdvice" transaction-manager="transactionManager">
                
            <tx:attributes>
                <tx:method name="find*" read-only="true"/>
                <tx:method name="*" isolation="DEFAULT">tx:method>
            tx:attributes>
        tx:advice>
        
        <aop:config>
            <aop:advisor advice-ref="txAdvice" pointcut="execution(* cn.okt.service.impl.*ServiceImpl.*(..))">aop:advisor>
        aop:config>
    
  13. 在控制层添加save方法

        @RequestMapping("/save")
        public void save(Account account, HttpServletRequest request, HttpServletResponse response) throws IOException {
            System.out.println("表现层:增加账户...");
            // 调用service的方法
            accountService.saveAccount(account);
            //重定向
            response.sendRedirect(request.getContextPath()+"/account/findAll");
        }
    
  14. 修改前端页面,并开启Tomcat测试

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    
    
        Title
    
    
    

    测试

    测试
    姓名:
    金额:

总结

归根到底我们要以Spring为核心对其他两个框架进行集成,如若上述测试都通过则代表你已经成功的整合了SSM环境,这时就可以进行项目的开发了。在此处我曾发生了一个让我抓狂的问题,就是在web.xml中将监听类写错了,导致我开启Tomcat时无法加载我的spring的配置文件,从而无法创建所有bean对象,所以一旦发生错误一定要好好看清配置文件是否有配错类,注解是否有漏加,这是典型的错误,毕竟人无完人,总有走神的时候,多加注意就好。

你可能感兴趣的:(java,spring,ssm)