How to integrate ssm

Posted by The_Black_Knight on Fri, 18 Feb 2022 10:13:45 +0100

SSM integration

  • Spring MVC presentation layer

  • Spring business layer

  • MyBatis persistence layer

Build environment

Create maven project in POM Pass in jar package in XML

<properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <maven.compiler.source>1.8</maven.compiler.source>
  <maven.compiler.target>1.8</maven.compiler.target>
  <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. Build the basic project document directory

Write Spring

3. Configure the xml file of spring framework, put it in the resources folder, introduce the label in the header, and start component scanning

<?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">

    <!--Enable annotation scanning-,Hope to deal with srvice and dao,controller No processing required-->
    <context:component-scan base-package="com.yuan">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    
</beans>

4. Annotate the class and submit it to IOC container management

5 test whether spring can run

@Test
public void run1(){
    //Load profile
    ApplicationContext context =
            new ClassPathXmlApplicationContext("applicationContext.xml");
    //Get object
    AccountService accountService = (AccountService) context.getBean("accountService");
    //Call method
    accountService.findAll();
}

Write spring MVC

On the web Adding components to XML

1. Configure Chinese garbled code filter

<!--Chinese garbled code filter-->
<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>

2. Add front-end controller

<!--Configure front-end controller-->
<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>

3 create a new spring MVC configuration file, start scanning, add a parser, and filter static resources

<?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:mvc="http://www.springframework.org/schema/mvc"
       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/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!--Enable annotation scanning, only scanning Controller annotation-->
    <context:component-scan base-package="com.yuan">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    <!--Configure view parser-->
    <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>
    <!--Filter static resources-->
    <mvc:resources mapping="/css/**" location="/css/" />
    <mvc:resources mapping="/images/**" location="/images/" />
    <mvc:resources mapping="/js/**" location="/js/" />
    <!--open springmvc Annotation support-->
    <mvc:annotation-driven/>

</beans>

4 write controller and test spring MVC layer

@Controller
@RequestMapping("/account")
public class AccountController {

    @RequestMapping("/findAll")
    public String findAll(){
        System.out.println("springmvc Presentation layer");
        return "list";
    }
}

Integrate spring and spring MVC

1 load the spring configuration file and start annotation scanning
It only says spring XML configuration file, but when we open tomcat, we need to read the configuration file on the web Introducing spring.xml into XML XML, the listener ContextLoaderListener is used here, and the default is to execute applicationContext.xml under WEB-INF XML, so we need to set the path of the file later

<!--to configure spring The default listener is only loaded WEB-INF Directory applicationContext.xml-->
<listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--Set the path of the configuration file-->
<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath:applicationContext.xml</param-value>
</context-param>

In this way, when we open the server, spring will automatically perform annotation scanning, create and inject objects into the IOC container for our use

2 add AccountService in the controller, inject dependency annotation, and then call the method of this object in the method

@Controller
@RequestMapping("/account")
public class AccountController {

    @Autowired
    private AccountService accountService;

    @RequestMapping("/findAll")
    public String findAll(){
        System.out.println("springmvc Presentation layer");
        //Call service business layer
        accountService.findAll();
        return "list";
    }

}

Write MyBatis

1. Configuration file

<?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:///ssm"/>
                <property name="username" value="root"/>
                <property name="password" value="yuan"/>
            </dataSource>
        </environment>
    </environments>

    <!--Configure mapped files-->
    <mappers>
        <package name="com.yuan.dao" />
    </mappers>

</configuration>

2. Use annotation development, so do not configure the corresponding mapping file. Just add annotation to the original interface

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);
}

3 test

public class TestMybatis {
    @Test
    public void run1() throws IOException {
        //Load the configuration file of mybatis
        InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(in);
        SqlSession session = factory.openSession();
        AccountDao accountDao = session.getMapper(AccountDao.class);

        List<Account> accounts = accountDao.findAll();
        for (Account account : accounts) {
            System.out.println(account);
        }
        session.close();
        in.close();
    }
    @Test
    public void run2() throws IOException {
        //Load the configuration file of mybatis
        InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(in);
        SqlSession session = factory.openSession();
        AccountDao accountDao = session.getMapper(AccountDao.class);

        Account account = new Account();
        account.setName("qwe");
        account.setMoney(123);

        accountDao.saveAccount(account);

        //Add, delete and modify transactions that need to be submitted
        session.commit();
        session.close();
        in.close();
    }
}

Integrate Spring and MyBatis

The proxy object generated by dynamic proxy in 1MyBatis can be added to the IOC container, and then the object can be injected into the service

Integrate the contents of SqlMapConfig, that is, the configuration file of Mybatis, into the configuration file of spring, so that SqlMapConfig can be deleted,

The specific configuration is as follows:

<!--Spring integration MyBatis-->
<!--Configure connection pool-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <property name="driverClass" value="com.mysql.jdbc.Driver"/>
    <property name="jdbcUrl" value="jdbc:mysql:///ssm"/>
    <property name="user" value="root"/>
    <property name="password" value="yuan"/>
</bean>

<!--Configure factory objects-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource"></property>
</bean>
<!--Configure the package where the interface is located-->
<bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com.yuan.dao"/>
</bean>

The above configuration file has created a factory. The factory has created a sqlsession object. The sqlsession object uses the dynamic agent to create the implementation class of the interface and put it in the IOC container

2 annotate the dao interface to add the proxy object to the IOC container

3. In the implementation class of service, the annotation * * @ Autowired * * is used to introduce dao implementation class proxy object in IOC container

@Service("accountService")
public class AccountServiceImpl implements AccountService {

    @Autowired
    public AccountDao accountDao;

    @Override
    public List<Account> findAll() {
        System.out.println("Business layer, query all account information...");
        return accountDao.findAll();
    }

    @Override
    public void saveAccount(Account account) {
        System.out.println("Business layer, save account information...");
        accountDao.saveAccount(account);
    }
}

Problem:
During configuration, mybatis can call the database operation, but if the configuration of mybatis is added to the spring configuration file, the database cannot be found. The reason is that the version of MySQL connection in pom is too low, and the version of c3p0 is incompatible with MySQL connection
The solution is
Change MySQL connexion to 8.0.11, and add a line of parameters to the url address when configuring the data source

<property name="jdbcUrl" value="jdbc:mysql:///ssm?serverTimezone=UTC"/>

Configure transactions
Under spring configuration file

<!--to configure spring Framework declarative transaction management-->
<!--Configure transaction manager-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <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(* com.yuan.service.impl.*ServiceImpl.*(..)))"></aop:advisor>
</aop:config>

Call total test

jsp page:

<a href="account/findAll">Test query</a>

<a href="account/findAll">Test save</a>
<form action="account/save" method="post">
    full name:<input type="text" name="name">
    amount of money:<input type="text" name="money">
    <input type="submit" value="preservation">
</form>

Controller class

@RequestMapping("/findAll")
public String findAll(Model model){
    System.out.println("springmvc Presentation layer");
    //Call service business layer
    List<Account> accounts = accountService.findAll();
    model.addAttribute("list",accounts);

    return "list";
}

@RequestMapping("save")
public String save(Account account){
    System.out.println("springmvc Presentation layer preservation...");
    accountService.saveAccount(account);
    return "list";

}

Topics: SSM