SSM framework integration

Posted by DyslexicDog on Wed, 05 Jan 2022 19:24:37 +0100

Catalogue of series articles

1.spring series articles
2. Spring MVC series articles
3.mtbatis series articles

preface

The common three-tier structure of Java EE, including presentation layer, business layer and data layer, can be built and developed with the help of spring MVC, spring and mybatis respectively. The main help of spring MVC is to help us process and respond to requests in a unified and simplified way. Spring mainly uses IoC and Aop to help us create and manage objects, manage things and quickly enhance methods. In fact, we can do these ourselves, but after using spring, individuals can obviously feel the simplification of code and the improvement of coding efficiency, and can completely focus on logical coding, The rest can be left to spring to help us manage. Mybatis is a complete replacement for jdbc. Just configure the mapping relationship and sql statements and you can put them into use.

I personally encountered two difficulties in integrating the SSM framework:
① When spring integrates mybatis, the creation of related objects of mybatis needs to be managed by springIoC.
② Loading of spring configuration file.

1, Environment construction

1. The spring MVC environment is built separately

tomcat, servlet, jsp project
pom file

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

Use spring MVC first and build the presentation layer first
The spring MVC configuration file is as follows:

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

	<!--tell springmvc Where do I need to scan annotations-->
    <context:component-scan base-package="com.mediacomm">
    	<!--tell springmvc Just focus on which annotations-->
        <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/page/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <!--Filter static resources-->
    <mvc:resources location="/css/" mapping="/css/**" />
    <mvc:resources location="/images/" mapping="/images/**" />
    <mvc:resources location="/js/" mapping="/js/**" />

    <!--open SpringMVC Annotation support-->
    <mvc:annotation-driven/>
</beans>

Note that I have used spring annotations to create objects and dependency injection

@Controller
@RequestMapping("/request")
public class First {

    @Autowired
    UserServiceImpl userService;

    @RequestMapping(path = "/findAll")
    public String findAllUser(){
        System.out.println("implement findall.......");
        List<User> users = userService.findAllUser();
        for (User user: users
             ) {
            System.out.println(user);
        }
        return "success";
    }

    @RequestMapping(path = "/addUser")
    public String addUser(User user){
        System.out.println(user);
        userService.saveUser(user);
        return "success";
    }
}

Main page

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

<html>
<body>
    <h2>Hello World!</h2><br>
    <a href="request/findAll">Find all users</a><br>
    <form action="request/addUser" method="post">
        full name:<input type="text" name="username"><br>
        password:<input type="password" name="password"><br>
        Address:<input type="text" name="address"><br>
        Deposit:<input type="text" name="money"><br>
        <input type="submit" name="Submit"><br>
    </form>
</body>
</html>

2.mybatis environment is built separately

Note that I have used spring annotations to create objects and dependency injection
dao layer

@Repository
public interface UserDao {

    @Select("select * from user")
    List<User> findAll();

    @Insert("insert into user(username,password,address,money) values(#{username},#{password},#{address},#{money})")
    void insertUser(User user);
}

service layer

@Service("userService")
public class UserServiceImpl {

    @Autowired
    private UserDao userDao;

    public List<User> findAllUser(){
        return userDao.findAll();
    }

    public void saveUser(User user){
        userDao.insertUser(user);
    }
}

2, spring integrates mybatis

A configuration file

<?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">
    
    <context:component-scan base-package="com.mediacomm">
    	<!--An ignore attribute is configured to ignore the specified annotation, so it will not be created twice, because in springmvc Used in@Controller Has been created for us-->
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!--Spring integration MyBatis frame-->
    <!--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:///day17"/>
        <property name="user" value="root"/>
        <property name="password" value="123456"/>
    </bean>

	<!--It's all used here mybatis For us org.mybatis.spring The package is dedicated to integrate into spring Medium-->
    <!--to configure SqlSessionFactory factory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
    </bean>
	
	<!--Scan specified dao Interface and will create a proxy object for us-->
    <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.mediacomm.dao"/>
    </bean>

	<!--This is spring Configuration of control transactions provided-->
    <!--affair-->
    <bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <tx:advice id="advice" transaction-manager="dataSourceTransactionManager">
        <tx:attributes>
            <tx:method name="find*" propagation="SUPPORTS"/>
            <tx:method name="*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>
    <aop:config>
        <aop:pointcut id="pt1" expression="execution(* com.mediacomm.service.*.*(..))"/>
        <aop:advisor advice-ref="advice" pointcut-ref="pt1"></aop:advisor>
    </aop:config>

2, Load spring configuration file

First, you need to know the servletContext. Second, you need to know the listener with a ServletContextListener
servletContext is a global (application wide) domain object. It is created when the tomcat server is started and destroyed when the tomcat server is shut down. The corresponding listener, ServletContextListener, is an interface that listens to its life cycle.
In spring, there is a class ContextLoaderListener that implements ServletContextListener, so you don't need to create it. You can use this listener directly.
On the project's web Configuration in XML file

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationspringconfig.xml</param-value>
  </context-param>

3, Testing

[2021-08-04 11:20:59,748] Artifact ssm:war: Artifact is deployed successfully
[2021-08-04 11:20:59,749] Artifact ssm:war: Deploy took 10,760 milliseconds
 implement findall.......
User{username='admin', password='admin', address='New Zealand', money=667.0, id=1}
User{username='ffff', password='123456', address='Mercury', money=1333.0, id=2}
User{username='Change', password='321', address='Transaction price..', money=1111.0, id=4}
User{username='aaa', password='112', address='Mars', money=1111.0, id=10}
User{username='ww', password='xx', address='11', money=1111.0, id=11}
User{username='gsrg', password='zz', address='gggg', money=1111.0, id=12}
User{username='12', password='wef', address='hhhh', money=1111.0, id=13}
User{username='ag', password='123kj1231lkr', address='xxx', money=1111.0, id=14}
User{username='wer', password='afef', address='Mars', money=1111.0, id=15}
User{username='gge', password='zfb', address='dd', money=1111.0, id=16}
User{username='admin', password='123321', address='I refuse', money=123.0, id=18}

4, Supplement

I have a whim. I don't want to integrate through the package of mybatis spring provided by mybatis
As we all know, there are only four common steps in the application of mybatis, so it's not enough for me to hand over these four objects to spring for management. However, the disadvantage is that there are multiple mybatis configuration files, and one interface class of each dao needs to be created in spring. I've studied this for the time being.

		// Load profile
        InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
        // Create SqlSessionFactory object
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        // Create SqlSession object
        SqlSession session = factory.openSession();
        // Get proxy object
        AccountDao dao = session.getMapper(AccountDao.class);

After trying, record the configuration steps. It is also feasible after testing
The spring configuration file is configured as follows:

	<!--Try configuring it yourself mybatis Hand over springIoC Administration-->
    <bean id="inputStream" class="org.apache.ibatis.io.Resources" factory-method="getResourceAsStream">
        <constructor-arg value="Mybatis.xml"></constructor-arg>
    </bean>
    <bean id="builder" class="org.apache.ibatis.session.SqlSessionFactoryBuilder"></bean>
    <bean id="sqlSessionFactory" factory-bean="builder" factory-method="build">
        <constructor-arg ref="inputStream"></constructor-arg>
    </bean>
    <bean id="session" factory-bean="sqlSessionFactory" factory-method="openSession"></bean>
    <bean id="userDao" factory-bean="session" factory-method="getMapper">
        <constructor-arg type="java.lang.Class" value="com.mediacomm.dao.UserDao"></constructor-arg>
    </bean>

Topics: Java