微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

SSM整合

整合思路

选择XML + 注解的方式

  1. 搭建整合的环境
  2. 配置Spring
  3. 配置SpringMVC,再使用Spring整合SpringMVC
  4. 配置Mybatis,最后使用Spring整合Mybatis

环境搭建

  1. 利用Maven骨架创建webapp项目,在pom.xml中导入依赖的坐标

    <properties>
        <!--版本锁定-->
        <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>
        <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>
        <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 -->
        <dependency>
          <groupId>org.mybatis</groupId>
          <artifactId>mybatis</artifactId>
          <version>${mybatis.version}</version>
        </dependency>
        <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. 创建数据库

    create table account(
    	id int primary key auto_increment,
    	name varchar(20),
    	money double
    );
    
  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. 创建dao层接口

    public interface AccountDao {
    
        /**
         * 查询所有账户
         * @return
         */
        List<Account> findAll();
    
        /**
         * 保存账户
         * @param account
         */
        void saveAccount(Account account);
    }
    
  5. 创建service层接口及其实现类

    public interface AccountService {
        /**
         * 查询所有账户
         * @return
         */
        List<Account> findAll();
    
        /**
         * 保存账户
         * @param account
         */
        void saveAccount(Account account);
    }
    
    public class AccountServiceImpl implements AccountService {
    
        private AccountDao accountDao;
    
        @Override
        public List<Account> findAll() {
            System.out.println("业务层:查询所有账户");
            return accountDao.findAll();
        }
    
        @Override
        public void saveAccount(Account account) {
            accountDao.saveAccount(account);
        }
    }
    
  6. 在resources目录下创建连接数据库属性文件jdbcConfig.properties

    jdbc.driver=com.MysqL.jdbc.Driver
    jdbc.url=jdbc:MysqL://localhost:3306/ssm?useUnicode=true&characterEncoding=utf-8&useSSL=false
    jdbc.username=root
    jdbc.password=...
    
  7. log4j.properties日志文件

    # Set root category priority to INFO and its only appender to CONSOLE.
    #log4j.rootCategory=INFO, CONSOLE            debug   info   warn error fatal
    log4j.rootCategory=info, CONSOLE, LOGFILE
    
    # Set the enterprise logger category to FATAL and its only appender to CONSOLE.
    log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE
    
    # CONSOLE is set to be a ConsoleAppender using a PatternLayout.
    log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
    log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
    log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
    
    # LOGFILE is set to be a File appender using a PatternLayout.
    log4j.appender.LOGFILE=org.apache.log4j.FileAppender
    log4j.appender.LOGFILE.File=d:\axis.log
    log4j.appender.LOGFILE.Append=true
    log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
    log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
    

配置Spring

  1. 在resources目录下创建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: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">
    
        <!--配置spring创建容器时要扫描的包-->
        <context:component-scan base-package="com.chenpeng">
            <!--配置要忽略的注解-->
            <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
        </context:component-scan>
    </beans>
    
  2. 在dao层接口上配置注解

    @Repository
    public interface AccountDao
    
  3. 为service层接口实现类配置注解

    @Service("accountService")
    public class AccountServiceImpl implements AccountService {
    
        @Autowired
        private AccountDao accountDao;
        ...
    }
    
  4. 创建测试类测试通过

    public class SpringTest {
        @Test
        public void testOne(){
            ApplicationContext ac = new ClasspathXmlApplicationContext("ApplicationContext.xml");
            AccountService as = ac.getBean("accountService", AccountService.class);
            as.findAll();
        }
    }
    

配置SpringMVC

  1. 在resources目录下创建SpringMVC配置文件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">
    
        <!--配置扫描Controller的注解,其他的不扫描-->
        <context:component-scan base-package="com.chenpeng">
            <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 name="suffix" value=".jsp"/>
        </bean>
    
        <!--配置哪些静态资源不过滤-->
        <mvc:resources location="/js/" mapping="/js/**"></mvc:resources>
        <mvc:resources location="/css/" mapping="/css/**"></mvc:resources>
        <mvc:resources location="/images/" mapping="/images/**"></mvc:resources>
        
        <!--配置开启spring注解mvc的支持-->
        <mvc:annotation-driven/>
    </beans>
    
  2. 在webapp/WEB-INF/目录下的web.xml中添加配置

    <!--配置前端控制器-->
      <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.dispatcherServlet</servlet-class>
        <init-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>classpath:SpringMVC.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
      </servlet>
      <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
      </servlet-mapping>
    <!--配置解决中文乱码问题-->  
      <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>
      </filter>
      <filter-mapping>
        <filter-name>characterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
      </filter-mapping>
    
  3. 创建控制器类com.chenpeng.controller.AccountController

    @Controller
    @RequestMapping(path = "/account")
    public class AccountController {
    
        @Autowired
        private AccountService accountService;
    
        @RequestMapping(path = "/findAll")
        public String findAll(Model model){
            System.out.println("表现层:查询所有账户");
            List<Account> list = accountService.findAll();
            model.addAttribute("list",list);
            return "success";
        }
    
        @RequestMapping(path = "/saveAccount")
        public void saveAccount(Account account, HttpServletRequest request, HttpServletResponse response) throws IOException {
            accountService.saveAccount(account);
            response.sendRedirect(request.getcontextpath()+"/account/findAll");
            return;
        }
    }
    
  4. 在webapp目录下创建index.jsp,在webapp/WEB-INF目录下创建pages目录,在其中创建success.jsp

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>Title</title>
    </head>
    <body>
        <a href="account/findAll">测试查询</a>
    
        <h3>测试保存</h3>
        <form action="account/saveAccount" 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" %>
    <html>
    <head>
        <title>Title</title>
    </head>
    <body>
    <h1>查询所有账户</h1>
    <c:forEach items="${list}" var="account">
        ${account.name}
    </c:forEach>
    </body>
    </html>
    

Spring整合SpringMVC

在web.xml中配置监听器ContextLoaderListener,该监听器可以监听ServletContext的创建和销毁,ServletContext的创建和销毁与Tomcat是同步的,而ContextLoaderListener认加载WEB-INF目录下的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>

配置Mybatis

  1. 在resources目录下创建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>
        <!--配置环境-->
        <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://localhost:3306/ssm"/>
                    <property name="username" value="root"/>
                    <property name="password" value="..."/>
                </dataSource>
            </environment>
        </environments>
        <!--配置mappers-->
        <mappers>
            <package name="com.chenpeng.dao"/>
        </mappers>
    </configuration>
    
  2. 为dao层方法配置注解

    @Repository
    public interface AccountDao {
    
        /**
         * 查询所有账户
         * @return
         */
        @Select("select * from account")
        List<Account> findAll();
    
        /**
         * 保存账户
         * @param account
         */
        @Insert("insert into account(name,money) values(#{name},#{money})")
        void saveAccount(Account account);
    }
    
  3. 创建测试类测试通过

    public class TestMybatis {
    
        private InputStream in;
        private sqlSession sqlSession;
        private AccountDao accountDao;
    
        @Before
        public void init() throws IOException {
            in = Resources.getResourceAsstream("sqlMapConfig.xml");
            sqlSessionFactory factory = new sqlSessionFactoryBuilder().build(in);
            sqlSession = factory.openSession(true);
            accountDao = sqlSession.getMapper(AccountDao.class);
        }
    
        @After
        public void destroy() throws IOException {
            sqlSession.close();
            in.close();
        }
    
        @Test
        public void testFindAll() {
            List<Account> list = accountDao.findAll();
            for (Account account : list) {
                System.out.println(account);
            }
    
        }
    
        @Test
        public void testSaveAccount(){
            Account account = new Account();
            account.setName("cc");
            account.setMoney(666.0);
            accountDao.saveAccount(account);
        }
    }
    

Spring整合Mybatis

让spring来管理sqlSession的创建,即在spring配置文件中配置sqlSessionFactory工厂,并且不再需要sqlMapConfig.xml,在ApplicationContext.xml中配置Mybatis

<!--Spring整合Mybatis框架-->
    <context:property-placeholder location="classpath:jdbcConfig.properties"/>
    <!--配置连接池-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>
    <!--配置sqlSession工厂-->
    <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.chenpeng.dao"/>
    </bean>

dao层接口中的保存方法需要为其添加事务控制,在ApplicationContext配置spring的声明式事务管理

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。