About SSM integration, it's enough to read this one ~ (nanny level hand-in-hand tutorial)

SSM (Spring + spring MVC + MyBatis) framework set is integrated by spring and MyBatis (spring MVC is part of spring), which is often used as the framework of web projects with simple data source.         

catalogue

1, Create a web project based on maven Management:

1.1 complete the project structure

1.2 add web project dependency and configure server running environment

2, Deploy mybatis:

2.1 add mybatis dependency and create configuration file

3, Deploy spring and springMvc:

3.1 adding dependencies

3.2 creating spring configuration files

3.3 configure front-end controller

4, Consolidation configuration:

4.1 Ioc configuration

4.1.1 configure Druid connection pool

4.1.2 configuring sqlsessionFactory

4.1.3 configuring mapperScannerConfigurer

4.2 Aop configuration

5, Unit test:

5.1 preparation before test

5.1.1 create entity classes based on database attributes

5.1.2 define interfaces in Dao package

5.2 Service layer based testing

5.2.1 create a mapping file in the mappers directory and configure it

5.2.2 create service layer interface

5.2.3 unit testing with junit

5.2.4 test results

5.3 Controller layer based testing

5.3.1 creating jsp pages

5.3.2 create Controller class

5.3.3 server test based on tomcat

1, Create a web project based on maven Management:

1.1 complete the project structure

Create a new project (new--file--project--maven), enter the appropriate project name and wait for the project to load. Add webapp folder under the same level directory of main, WEB-INF folder under webapp folder and WEB-INF folder under WEB-INF folder XML file, modify POM XML file, add the packing tag as war, refresh, and you will see a "little blue ball" in the webapp folder

 <groupId>com.xgsm</groupId>
    <artifactId>Ssm-demo01</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

1.2 add web project dependency and configure server running environment

Adding web project dependencies is to add servlet API and jsp jar packages. There are two ways to add them. The first is to add tomcat through project Structure---Modules. After adding successfully, the servlet API and jsp jar packages will be automatically imported. One problem with this way is that when we migrate the project, errors will be reported due to different environments, so it is not recommended; The other is to manually add the dependencies of the two jar packages to POM In XML files, this addition method is more portable.

   <!--add to web Project dependency (can also be imported) tomcat Add)-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.0</version>
            <scope>provided</scope>
        </dependency>
        <!-- api -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>

Configuring the server running environment is to add a tomcat server. Click Edit Configurations to add a local tomcat server. First, click Fix to deploy the project war to the server

II. Deploy mybatis:

2.1 add mybatis dependency and create configuration file

Add mybatis dependency and lombok dependency;

 <!--add to mybatis rely on-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>
        <!--add to mysql-connection-java rely on -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.44</version>
        </dependency>
        <!--add to lombok rely on -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
        </dependency>

In ssm integration, since the data connection pool and other information are configured by spring integration, mybatis config XML files are optional, but there will be other configuration requirements in later project development. Therefore, the mybatis core configuration file is retained here, but no configuration is carried out.

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

3, Deploy spring and springMvc:

3.1 adding dependencies

Due to the large number of dependencies required, if the jar package version needs to be changed later, it needs to be changed one by one, which seriously affects the efficiency and is inconvenient. Therefore, we adopt the unified version configuration here. The required jar packages include: Spring context, spring aspects, spring JDBC, spring test, spring web, spring webmvc and JSON databind

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.xgsm</groupId>
    <artifactId>Ssm-demo01</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>
    <!--Set the same version number-->
    <properties>
        <spring.version>5.2.13.RELEASE</spring.version>
    </properties>

  
        <!--add to spring,springmvc rely on-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- spring-context -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- spring-jdbc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- spring-test -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
            <scope>test</scope>
        </dependency>
        <!-- spring-webmvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- spring-web -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- jackson-databind -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.13.2.1</version>
        </dependency>

       
   
    </dependencies>
</project>

3.2 create Spring configuration file

In the past, when we wrote the project, we found that the spring configuration file and the spring MVC configuration file can be said to be "the same", but now when we integrate ssm, if all the configuration files are written in one file, it will appear very messy and inconvenient to maintain. Therefore, we adopt the method of multiple configuration files to configure separately during the integration, as follows:

1,spring-context.xml: only annotation declaration and class management

<?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"
       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">
    <!--Only annotation declaration and class management are configured-->
    <!--Declare using annotation configuration-->
    <Context:annotation-config/>
    <!--statement Spring Scan range of factory notes-->
    <Context:component-scan base-package="com.xgsm"/>
</beans>

2, spring-mvc.xml: MVC related configuration, such as static resource, interceptor, view parser, date converter configuration, etc

<?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: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/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd
       http://www.springframework.org/schema/mvc
      http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!--statement mvc Use annotation configuration-->
    <mvc:annotation-driven/>

    <mvc:default-servlet-handler></mvc:default-servlet-handler>
    <!--Release static resources-->
    <mvc:resources mapping="/css/**" location="/css/"/>
    <mvc:resources mapping="/js/**" location="/js/"/>
    <mvc:resources mapping="/imgs/**" location="/imgs/"/>
    <!--view resolver -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <!--Need to add jstl rely on-->
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
        <property name="prefix" value="/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
</beans>

 3,spring-mybatis.xml: related configuration of spring and mybatis integration

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

3.3 configure front-end controller

Configure the front-end controller on the web XML file. Since the multi configuration file method is used now, it will be slightly adjusted from the previous configuration method, as follows:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
    <servlet>
        <servlet-name>springMvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <!-- It adopts the method of multiple configuration files, so it is used when introducing addresses spring-*-->
            <param-value>classpath:spring-*.xml</param-value>
        </init-param>
        <!--Load on server startup-->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springMvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

4, Consolidation configuration:

4.1 Ioc configuration:

4.1.1 configure Druid connection pool

You can use any connection pool you need. You only need to import related dependencies. If you use C3P0 to add C3P0, here I use Druid connection pool, so you need to import Druid dependencies

    <!-- druid -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.9</version>
        </dependency>

Create Druid Properties external file

druid.driver =com.mysql.jdbc.Driver
druid.url =  jdbc:mysql://localhost:3306/tanke
druid.userName = root
druid.password = 990501
#Number of initialized connections
druid.pool.init=3
#After the peak, keep the number of connections
druid.pool.minIdle = 5
#Maximum number of connections that can be created during peak periods
druid.pool.MaxActive = 20
#Waiting time
durid.pool.timeout = 3000

In spring mybatis Configure the Druid data source in the XML file. Before configuration, you need to use the < context: Property placeholder > tag to introduce Druid Properties external file. It is worth noting that this tag can only be used once.

    <!-- Imported external files can only be used once-->
    <Context:property-placeholder location="classpath:druid.properties"/>
    <!--Configure data source-->
    <bean id="druidDataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${druid.driver}"/>
        <property name="url" value="${druid.url}"/>
        <property name="username" value="${druid.userName}"/>
        <property name="password" value="${druid.password}"/>
        <property name="initialSize" value="${druid.pool.init}"/>
        <property name="minIdle" value="${druid.pool.minIdle}"/>
        <property name="maxActive" value="${druid.pool.MaxActive}"/>
        <property name="maxWait" value="${durid.pool.timeout}"/>
    </bean>
   

4.1.2 configuring sqlsessionFactory

sqlsessionFactory is equivalent to the connection factory between mybatis and the database, so the data source needs to be injected during configuration. When configuring sqlsessionFactory, you can introduce mapping file address, alias entity, mybatis configuration file, etc. The details are as follows.

 <!--to configure sqlsessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--Configure data source-->
        <property name="dataSource" ref="druidDataSource"/>
        <!--to configure mapper Path of-->
        <property name="mapperLocations" value="classpath*:mappers/*Mapper.xml"/>

        <!--Configure the package of entity classes that need to define aliases-->
        <property name="typeAliasesPackage" value="com.xgsm.pojo"/>
        <!--Configuration needs mybatis Master profile for-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
    </bean>

4.1.3 configuring mapperScannerConfigurer

mapperScannerConfigurer is used by the spring container, so id attribute is not required. It is used to load all Dao files and create Dao objects into the spring container. However, Dao creation objects are created through getMapper, which is obtained through sqlsession and sqlsession is obtained through sqlsessionFactory. Therefore, sqlsessionFactory needs to be allocated to mapperScannerConfigurer first. The specific configuration is as follows:

    <!--to configure mapperScannerConfigurer-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--Inject session factory-->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <!--Declare the location of the interface-->
        <property name="basePackage" value="com.xgsm.Dao"/>
    </bean>

4.2 Aop configuration

Aop is also configured in spring mybatis XML file, and use the annotation based transaction management provided by spring to complete the transaction management of Dao layer operations. It is necessary to configure the transaction management aspect class provided by spring to the spring container. Since the transaction management class completes the management transaction based on the database connection, the data source should be configured to the transaction management class. The specific configuration is as follows:

  <!--integration aop   Annotation based transaction management strategy-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="druidDataSource"/>
    </bean>
    <!--Declare transaction management policy using annotations-->
    <tx:annotation-driven transaction-manager="transactionManager"/>

5, Unit test:

5.1 preparation before test

5.1.1 create entity classes based on database attributes

The code of database dump file is as follows:

CREATE DATABASE /*!32312 IF NOT EXISTS*/`tanke` /*!40100 DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci */ /*!80016 DEFAULT ENCRYPTION='N' */;

USE `tanke`;

/*Table structure for table `user` */

DROP TABLE IF EXISTS `user`;

CREATE TABLE `user` (
  `userid` int NOT NULL AUTO_INCREMENT,
  `username` varchar(20) NOT NULL,
  `password` varchar(25) NOT NULL,
  PRIMARY KEY (`userid`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

/*Data for the table `user` */

insert  into `user`(`userid`,`username`,`password`) values (1,'admin','123456');

The entity classes created with lombok according to the database properties are as follows:

package com.xgsm.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;


@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class User {
    private int userId;
    private  String userName;
    private  String passWord;

}

5.1.2 define interfaces in Dao package

The function of querying whether the user login exists according to the example. Use the @ Component annotation provided by spring to inject the defined interface into the spring container. The interface definition is as follows:

package com.xgsm.Dao;

import com.xgsm.pojo.User;
import org.springframework.stereotype.Component;

@Component
public interface UserDao {
    public User QueryUser(String userName);
}

5.2 testing based on Service layer

5.2.1 create a mapping file in the mappers directory and configure it

The mappers mapping file package should be created under the resources resource package. After creating the mapper mapping file, the query operation and mapping can be realized.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org/DTD Mapper 3.0" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.xgsm.Dao.UserDao">
    <resultMap id="userMap" type="user">
        <id column="userid" property="userId"/>
        <result column="username" property="userName"/>
        <result column="password" property="passWord"/>
    </resultMap>

    <select id="QueryUser" resultMap="userMap">
        SELECT userid,username,password
        FROM user WHERE  username =#{userName}
    </select>
</mapper>     

5.2.2 create service layer interface

Create a Service interface, implement the Service interface, and use the @ Resource annotation to realize the automatic injection of UserDao

package com.xgsm.Service.ServiceImp;

import com.xgsm.Dao.UserDao;
import com.xgsm.Service.UserDaoService;
import com.xgsm.pojo.User;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class UserDaoServiceImp implements UserDaoService {
    @Resource
    private UserDao userDao;
    public User QueryUser(String userName) {
        return userDao.QueryUser(userName);
    }
}

Add junit dependency

 <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>

Then use junit implementation to test Dao layer interface

package com.xgsm.Dao;

import com.xgsm.pojo.User;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.annotation.Resource;

import static org.junit.Assert.*;


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:spring-context.xml","classpath:spring-mvc.xml","classpath:spring-mybatis.xml"})
public class UserDaoTest {
    @Resource
    private UserDao userDao;
    @Test
    public void queryUser() throws Exception {
        User user = userDao.QueryUser("admin");
        System.out.println(user);
    }


}

5.2.4 test results

Print user when username = 'admin' is found. If it is not found, print 'null'

5.3 Controller layer based testing

5.3.1 creating jsp pages

Create index JSP, create a new form in the page. There are two input boxes in the form, which are user and password. And set the submission address and submission method, as follows:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form action="user/login" method="post">
    <p>user name<input type="text" name="userName"></p>
    <p>password<input type="text" name="passWord"></p>
    <p><input type="submit" ></p>
</form>
</body>
</html>

5.3.2 create Controller class:

Call serviceImp in the Controller class. When passing parameters from the front end to the back end, if the parameters in the method are the same as the "name" attribute value in the front-end form, you can omit the @ RequestParam annotation. Finally, use the Model to pass the value of the queried user object to success JSP page, the specific code is as follows;

package com.xgsm.Controllers;

import com.xgsm.Service.UserDaoService;
import com.xgsm.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;


@Controller
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserDaoService userDaoService;

    @RequestMapping("/login")
    public String userLogin( String userName, Model model) {
        User user = userDaoService.QueryUser(userName);
        System.out.println(user);
        model.addAttribute("user",user);
        return "success";
    }
}

5.3.3 server test based on tomcat

SSM controller test

Tags: Java MySQL Maven Spring SQL

Posted by xxreenaxx1 on Thu, 05 May 2022 12:34:15 +0300