Integration of ssm framework (spring+ springMVC+MyBatis)

SSM framework integration

1. Construction environment

1.1 create data table

  • The MySQL database is used to create a database named ssm and a table named account.
CREATE DATABASE ssm;
USE ssm;
CREATE TABLE account(
id INT PRIMARY KEY auto_increment,
NAME VARCHAR(20),
money DOUBLE
);

1.2 create project

  • This project uses IDEA as the writing tool, based on maven's WEB project. First, create a new Project, as shown in the following figure;

    [failed to transfer the pictures in the external link. The source station may have anti-theft chain mechanism. It is recommended to save the pictures and upload them directly (img-SP4JsZQt-1579081351866)(C:\Users\yulu\Desktop \ temporary \ img_1.png))

    Then select Next, the interface is as follows, and fill in the relevant information of the project;

    [failed to save the image in the external link. The source station may have anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-hN4kd2I9-1579081351867)(C:\Users\yulu\Desktop \ temporary \ img_2.jpg))

Then select Next. The interface is as follows. Select the corresponding maven version;

[failed to transfer the pictures in the external link. The source station may have anti-theft chain mechanism. It is recommended to save the pictures and upload them directly (img-n0TSHUre-1579081351867)(C:\Users\yulu\Desktop \ temporary \ img_. PNG))

Then select Next. The interface is as follows. Select the path of project creation;

[failed to transfer the pictures in the external link. The source station may have anti-theft chain mechanism. It is recommended to save the pictures and upload them directly (img-Rc9dfeJX-1579081351867)(C:\Users\yulu\Desktop \ temporary \ img_. PNG))

Then select Finish, and the console will prompt [INFO] BUILD SUCCESS even if the project is completed.

1.3 introduce relevant maven coordinates.

  • As there are many coordinates to be introduced, they are not listed here.

1.4 create package and write basic code.

  • The basic directory structure of the specific project is shown in the figure below.

    [failed to transfer the pictures in the external link. The source station may have anti-theft chain mechanism. It is recommended to save the pictures and upload them directly (img-R1fVs2i9-1579081351868)(C:\Users\yulu\Desktop \ temporary \ img_. PNG))

2. Build the Spring framework and test it.

2.1 writing 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">

    <!--Turn on scanning for annotations ,Only deal with service and dao-->
    <context:component-scan base-package="cn.****">
        <!--Configure which annotations are not scanned-->
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

</beans>

2.2 Log4j configuration file 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 testing whether the spring framework can be used

  • Write a test class, give our AccountService to the spring container to create for us, and test whether it is normal.

    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(){
            //Load the configuration file for spring
            ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
            //Get objects
            AccountService as = (AccountService) ac.getBean("accountService");
            //Calling method
            as.findAll();
        }
    }
    
    

3. Build spring MVC framework and test

3.1 write web.xml

  • Configure the front-end controller and solve the Chinese confusion.

    <!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>
      
      <!--Configure front end controller-->
      <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--Load springmvc.xml Profile for-->
        <!--Start the server and create the 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>
      
      <!--The filter to solve the Chinese disorder-->
      <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 write springmvc.xml

  • Configure the package to be scanned for spring MVC annotation, view parser, static resources to be filtered, and enable spring MVC annotation support.

    <?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">
    
        <!--Enable annotation scanning-->
        <context:component-scan base-package="cn.****">
            <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
        </context:component-scan>
    
        <!--Configure view parser object-->
        <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>
    
        <!--Filtering static resources-->
        <mvc:resources mapping="/css/**" location="/css/"></mvc:resources>
        <mvc:resources mapping="/images/**" location="/images/"></mvc:resources>
        <mvc:resources mapping="/js/**" location="/js/"></mvc:resources>
    
        <!--open springMVC Annotation support for-->
        <mvc:annotation-driven />
    
    </beans>
    

3.3 test

  • Write a hyperlink in 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">test</a>
    </body>
    </html>
    
  • Write AccountController.java, and finally start the server to see if it can execute successfully.

    package cn.****.controller;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    /**
    
    - Account WEB
      */
      @Controller
      @RequestMapping("/account")
      public class AccountController {
    
      @RequestMapping("/findAll")
      public String findAll(){
          System.out.println("Presentation layer, query all information...");
          return "list";
      }
      }
    

4.Spring framework integrates spring MVC

4.1 configuration when the server starts, it also needs to load the spring configuration file, so you need to add configuration to the web.xml file.

<!--To configure spring Listener,Load only by default WEB/INF Directory applicationContext.xml configuration file-->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <!--Set path to profile-->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
  • At this point, the controller can create the service object through dependency injection and call.

5. Build the Mybatis framework and test it.

5.1 write the basic configuration file SqlMapConfig.xml of the database

<?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>
    <!--Configuration environment-->
    <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>
    <!--Imported color response profile-->
    <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 to write sql statements, you can either annotate or map files.

  • In the way of annotation, you only need to write sql statements on the methods in dao interface, for example:

    //Query all account information
    @Select("select * from account")
    public List<Account> findAll();
    

5.3 write test method

@Test
public void run1() throws IOException {
    //Load the configuration file of mybatis
    InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
    //Create SqlSessionFactory object
    SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
    //Create SqlSeeion object
    SqlSession seession = factory.openSession();
    //Get proxy object
    AccountDao dao = seession.getMapper(AccountDao.class);
    //Query all data
    List<Account> list = dao.findAll();
    for (Account account : list) {
        System.out.println(account);
    }
    //close resource
    seession.close();
    in.close();
}

6. Spring framework integrates Mybatis framework

6.1 transfer the related configuration files of Mybatis to the configuration files of Spring.

  • The connection pool, SqlSessionFactory factory, the package where the interface is configured, and the Spring framework declarative transaction management will be configured.

    <!--spring integration Mybatis frame-->
        <!--Configure connection pool-->
        <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>
        <!--To configure SqlSeeionFactory factory-->
        <bean class="org.mybatis.spring.SqlSessionFactoryBean" id="sqlSessionFactory">
            <property name="dataSource" ref="dataSource"></property>
        </bean>
        <!--Configure the package of the interface-->
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" id="mapperScannerConfigurer">
            <property name="basePackage" value="cn.***.dao"></property>
        </bean>
    
        <!--To configure Spring Framework declarative transaction management-->
        <!--Configure transaction manager-->
        <bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager" id="transactionManager">
            <property name="dataSource" ref="dataSource"></property>
        </bean>
        <!--Configure notifications for transactions-->
        <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>
        <!--To configure AOP Enhance-->
        <aop:config>
            <aop:advisor advice-ref="txAdvice" pointcut="execution(* cn.****.service.impl.*ServiceImpl.*(..))"/>
        </aop:config>
    
Published 8 original articles, won praise 6, visited 1497
Private letter follow

Tags: Spring log4j xml Mybatis

Posted on Wed, 15 Jan 2020 08:14:23 -0500 by maxsslade