ssm框架的整合(spring+ springMVC+MyBatis)

SSM框架整合

1.搭建环境

1.1 创建数据表

  • 使用的是MySQL数据库,创建数据库名为ssm,再创建一张名为account的表。
CREATE DATABASE ssm;
USE ssm;
CREATE TABLE account(
id INT PRIMARY KEY auto_increment,
NAME VARCHAR(20),
money DOUBLE
);

1.2 创建项目

  • 本项目使用的是编写工具为IDEA,基于maven的WEB项目,首先新建项目new Project,如下图;

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-SP4JsZQt-1579081351866)(C:\Users\yulu\Desktop\临时\img_1.png)]

    然后选择Next,界面如下,填写项目有关信息;

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-hN4kd2I9-1579081351867)(C:\Users\yulu\Desktop\临时\img_2.jpg)]

然后选择Next,界面如下,选择对应的maven版本;

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-n0TSHUre-1579081351867)(C:\Users\yulu\Desktop\临时\img_3.png)]

然后选择Next,界面如下,选择项目创建的路径;

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Rc9dfeJX-1579081351867)(C:\Users\yulu\Desktop\临时\img_4.png)]

然后选择Finish,此时,项目就算构建完成了,控制台会提示[INFO] BUILD SUCCESS。

1.3 引入相关的maven座标。

  • 由于需要引入的座标比较多这里没有列举。

1.4 创建包,以及编写基本代码。

  • 具体项目基本目录结构如下图。

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-R1fVs2i9-1579081351868)(C:\Users\yulu\Desktop\临时\img_5.png)]

2. 搭建Spring框架并测试。

2.1 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"
       xmlns:spring="http://www.springframework.org/schema/tool"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://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 http://www.springframework.org/schema/tool http://www.springframework.org/schema/tool/spring-tool.xsd">

    <!--开启注解的扫描 ,只处理service和dao-->
    <context:component-scan base-package="cn.****">
        <!--配置哪些注解不扫描-->
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

</beans>

2.2 Log4j的配置文件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

2.3测试spring框架是否可以使用

  • 编写一个测试类,将我们的AccountService交给spring容器为我们创建,测试是否正常。

    package cn.****.test;
    
    import cn.****.service.AccountService;
    import org.junit.Test;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    public class TestSpring {
    
        @Test
        public void run1(){
            //加载spring的配置文件
            ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
            //获取对象
            AccountService as = (AccountService) ac.getBean("accountService");
            //调用方法
            as.findAll();
        }
    }
    
    

3. 搭建SpringMVC框架,并测试

3.1编写web.xml

  • 配置前端控制器和解决中文乱码。

    <!DOCTYPE web-app PUBLIC
     "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
     "http://java.sun.com/dtd/web-app_2_3.dtd" >
    
    <web-app>
      <display-name>Archetype Created Web Application</display-name>
      
      <!--配置前端控制器-->
      <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--加载springmvc.xml的配置文件-->
        <!--启动服务器就创建该servlet-->
        <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>
    </web-app>
    
    

3.2 编写springmvc.xml

  • 配置springmvc注解要扫描的包,视图解析器,配置需要过滤的静态资源,开启springMVC的注解支持。

    <?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
            https://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/mvc
            https://www.springframework.org/schema/mvc/spring-mvc.xsd
            http://www.springframework.org/schema/context
            https://www.springframework.org/schema/context/spring-context.xsd">
    
        <!--开启注解扫描-->
        <context:component-scan base-package="cn.****">
            <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
        </context:component-scan>
    
        <!--配置视图解析器对象-->
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="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>
    
        <!--开启springMVC的注解支持-->
        <mvc:annotation-driven />
    
    </beans>
    

3.3 测试

  • 在index.jsp中写一个超链接。

    <%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="utf-8" %>
    <html>
    <head>
        <title>index</title>
    </head>
    <body>
    <h3>index</h3>
    <a href="account/findAll">测试</a>
    </body>
    </html>
    
  • 编写AccountController.java,最后启动服务器看是否能够执行成功。

    package cn.****.controller;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    /**
    
    - 账户WEB
      */
      @Controller
      @RequestMapping("/account")
      public class AccountController {
    
      @RequestMapping("/findAll")
      public String findAll(){
          System.out.println("表现层,查询所有的信息。。。");
          return "list";
      }
      }
    

4.Spring框架整合SpringMVC

4.1 配置当服务器启动时同时也需要加载spring的配置文件,所以需要在web.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>
  • 此时,controller就可以通过依赖注入的方式创建service对象,并调用。

5. 搭建Mybatis框架,并测试。

5.1 编写数据库的基本配置文件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"></transactionManager>
            <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="root"/>
            </dataSource>
        </environment>
    </environments>
    <!--引入的应色配置文件-->
    <mappers>
<!--        <mapper resource="cn/****/dao/xxx.xml"></mapper>-->
<!--        <mapper class="cn.****.dao.AccountDao"></mapper>-->
<!--        <mapper class="cn.****.dao.UserDao"></mapper>-->
        <package name="cn.****.dao"/>
    </mappers>

</configuration>

5.2 编写sql语句,可以采用注解的方式,也可以采用映射文件的方式。

  • 采用注解的方式,只需在dao接口里的方法上面编写sql语句,例如:

    //查询所有账户信息
    @Select("select * from account")
    public List<Account> findAll();
    

5.3 编写测试方法

@Test
public void run1() throws IOException {
    //加载mybatis的配置文件
    InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
    //创建SqlSessionFactory对象
    SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
    //创建SqlSeeion对象
    SqlSession seession = factory.openSession();
    //获取代理对象
    AccountDao dao = seession.getMapper(AccountDao.class);
    //查询所有的数据
    List<Account> list = dao.findAll();
    for (Account account : list) {
        System.out.println(account);
    }
    //关闭资源
    seession.close();
    in.close();
}

6. Spring框架整合Mybatis框架

6.1 将Mybatis的相关的配置文件转移到Spring的配置文件中。

  • 将配置连接池,配置SqlSessionFactory工厂,配置接口所在的包,以及Spring框架声明式事务管理等。

    <!--spring整合Mybatis框架-->
        <!--配置连接池-->
        <bean class="com.mchange.v2.c3p0.ComboPooledDataSource" id="dataSource">
            <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
            <property name="jdbcUrl" value="jdbc:mysql://localhost/ssm"></property>
            <property name="user" value="root"></property>
            <property name="password" value="root"></property>
        </bean>
        <!--配置SqlSeeionFactory工厂-->
        <bean class="org.mybatis.spring.SqlSessionFactoryBean" id="sqlSessionFactory">
            <property name="dataSource" ref="dataSource"></property>
        </bean>
        <!--配置接口所在的包-->
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" id="mapperScannerConfigurer">
            <property name="basePackage" value="cn.***.dao"></property>
        </bean>
    
        <!--配置Spring框架声明式事务管理-->
        <!--配置事务管理器-->
        <bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager" id="transactionManager">
            <property name="dataSource" ref="dataSource"></property>
        </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(* cn.****.service.impl.*ServiceImpl.*(..))"/>
        </aop:config>
    
发布了11 篇原创文章 · 获赞 7 · 访问量 1732
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章