SSM infrastructure integration

Keywords: Java Maven Spring SSM

SSM infrastructure integration

Before integrating a spring + spring MVC + mybatis project, we need to understand their respective functions?

  1. What is Spring, what is it used for, and what is its main function in SSM?

    Spring is an open source lightweight Java development framework, which is used to simplify the development of applications (for details, see: Spring Framework ). In SSM, Spring is mainly responsible for the management of business objects.

  2. What about spring MVC?

    Spring mvc is a module of the spring framework and a web framework module based on mvc (see the following for details: Web on Servlet Stack (spring.io) ). Spring MVC in SSM, spring MVC is mainly responsible for handling client requests, forwarding and page management. For details, see:

  3. What about Mybatis?

    MyBatis is an excellent persistence layer framework, which supports custom SQL, stored procedures and advanced mapping (for details, see: https://mybatis.org/mybatis-3/zh/index.html ).

After understanding their respective functions, we began to gradually integrate an SSM project.

Prepare project environment: jdk1.8, maven, idea

1, Build a Maven project

1. Create a new Maven project using IDEA

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-ekadg58l-1633981381695)(C:\Users \ Feng Yongbin \ appdata \ roaming \ typora user images \ image-20211012001418050. PNG)]

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-fIf1I7nJ-1633981381696)(C:\Users \ Feng Yongbin \ appdata \ roaming \ typora \ typora user images \ image-20211012001429314. PNG)]

2. Configure Maven's pom.xml and import project related jar packages

<?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.feng</groupId>
    <artifactId>SSM</artifactId>
    <version>1.0-SNAPSHOT</version>

    <!--Declare that items are printed when packaged jar package-->
    <packaging>jar</packaging>

    <dependencies>
        <!--Import spring Framework dependency-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.10</version>
        </dependency>

        <!--Import unit test dependencies for test Unit testing in-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13</version>
            <scope>test</scope>
        </dependency>

        <!--Import mysql Connection driven dependency-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.26</version>
        </dependency>

        <!--Import mybatis Framework dependency-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.7</version>
        </dependency>

        <!--Support integration spring Administration mybatis rely on-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.6</version>
        </dependency>

        <!--open spring Database connection support dependency-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.10</version>
        </dependency>

        <!--Import druid Connection pool management dependency for configuration mybatis Database connection pool-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.6</version>
        </dependency>

        <!--Import spring Test dependencies for support spring Conduct unit tests-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.3.10</version>
            <scope>test</scope>
        </dependency>

        <!--Import servlet-api Dependency, used to support servlet-->
        <dependency>
            <groupId>org.apache.tomcat</groupId>
            <artifactId>servlet-api</artifactId>
            <version>6.0.29</version>
        </dependency>

    </dependencies>

    <!--statement maven Which files need to be exported when packaging-->
    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>
    </build>

    <!--Declaration use java8 Compile-->
    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
</project>

2, Create project directory

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-ez5BBv7C-1633981381698)(C:\Users \ Feng Yongbin \ appdata \ roaming \ typora user images \ image-20211012003129107. PNG)]

3, MVC architecture corresponding to SSM

In the MVC three-tier architecture, there are presentation layer, business layer and persistence layer. Corresponding to SSM, Spring MVC is responsible for the business layer (request, view parsing, etc.), Spring is responsible for the business layer (creation and management of business objects), and Mybatis is is responsible for the persistence layer (data persistence processing).

So,

In the presentation layer: we mainly need to configure the dispatcher servlet (central controller), register the processor mapper, processor adapter and view parser.

In the business layer: we mainly need to register each Service.

In the persistence layer: we need to configure the data source and register Spring to take over the SqlSessionFactory of Mybatis.

Before configuration, we usually create a subfolder under the "resources" folder to represent the framework technologies we use. For example, create a "mybatis" folder under the "resources" file to store the configuration file of mybatis, as shown in the following figure:

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-g6eY1TLy-1633981381698)(C:\Users \ Feng Yongbin \ appdata \ roaming \ typora user images \ image-20211012005105105308. PNG)]

3, Configure Mybatis

1. Create mybatis-config.xml

In SSM, mybatis is managed by spring. We can directly set the properties related to mybatis in spring. But I'm still used to configuring some basic properties in the configuration file of mybatis. For example, the following configuration configures mybatis log output and entity class alias. See the following for specific configuration: https://mybatis.org/mybatis-3/configuration.html

<?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 log output to console-->
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>

    <!--Configure alias-->
    <typeAliases>
        <package name="com.feng.pojo"/>
    </typeAliases>

</configuration>

2. Entity class alias

Why configure entity class aliases? Of course, it can not be configured. The main purpose of configuring entity class aliases is to easily and quickly configure parameter types when writing XXXMapper.xml. The alias defaults to the entity class name and is not case sensitive.

For example:

  • Do not configure entity class alias:

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-UuzIk4lg-1633981381699)(C:\Users \ Feng Yongbin \ appdata \ roaming \ typora \ typora user images \ image-20211012010057442. PNG)]

  • After configuring the entity class alias:

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-zla8wtco-1633981381701)(C:\Users \ Feng Yongbin \ appdata \ roaming \ typora user images \ image-20211012010141255. PNG)]

4, Configure presentation layer

Configuring the presentation layer is actually configuring some related components of spring MVC. In configuring spring MVC, we mainly configure dispatcherservlet (central controller) and processor mapper, processor adapter and view parser.

1. Configure web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         version="2.5">

    <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><!--Add central controller-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring/applicationContext.xml</param-value><!--load spring container-->
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    
    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

The main thing is to add DispatcherServlet.

2. Create SpringMVC.xml

  • First, we create a springMvc.xml configuration file in the spring folder of the / resources / directory.

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-V23XYoGC-1633981381702)(C:\Users \ Feng Yongbin \ appdata \ roaming \ typora user images \ image-20211012015521159. PNG)]

3. Configure springMvc.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:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       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
">

    <!--Automatically register processor mapper, processor adapter-->
    <mvc:annotation-driven/>

    <!--Static resource filtering-->
    <mvc:default-servlet-handler/>

    <!--Register view parser-->
    <bean id="internalResourceViewResolver" 			class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"></property><!--Prefix, the file directory where the page is stored-->
        <property name="suffix" value=".jsp"></property><!--Suffix, type of page-->
    </bean>

    <!--Scan all controller-->
    <context:component-scan base-package="com.feng.controller"/>
</beans>
  • In springMvc.xml, we mainly configure static resource filtering, processor mapper, processor adapter and view parser.

  • Using < MVC: annotation driven / > we can automatically register the processor mapper and processor adapter, unlike the view parser, which requires manual registration, provided that there is xmlns:mvc=“ http://www.springframework.org/schema/mvc ”And xsi: schemaLocation “ http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd ”.

So far, the basic configuration of spring MVC has been completed.

5, Configure Service layer

1. Create applicationService.xml

	First of all, we are/resources/Catalog spring Create a folder applicationService.xml Configuration file.

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (IMG msngvhsf-1633981381703) (C: \ users \ Feng Yongbin \ appdata \ roaming \ typora user images \ image-20211012023253246. PNG)]

2. Configure applicationService.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:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
         http://www.springframework.org/schema/context
          https://www.springframework.org/schema/context/spring-context.xsd">

    <!--Method 1: turn on automatic scanning and scan com.feng.service Package all service And register with IOC In the container,
              The premise is that each Service All classes must have@Service annotation-->
    <context:component-scan base-package="com.feng.service"/>

    <!--Method 2: manually register each Service-->
    <bean id="doctorService" class="com.feng.service.impl.DoctorServiceImpl"/>

</beans>

In fact, it is to register each of our services. The configuration of transaction management will not be described for the time being.

6, Spring integrates Mybatis

1. Create applicationDao.xml

First, we create an applicationDao.xml configuration file in the spring folder of the / resources / directory.

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-v8Sdqk30-1633981381703)(C:\Users \ Feng Yongbin \ appdata \ roaming \ typora \ typora user images \ image-20211012024355495. PNG)]

2. Configure applicationDao.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:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd
">

    <!--Load database configuration file-->
    <context:property-placeholder location="classpath:db.properties"></context:property-placeholder>

    <!--Configure database connection pool-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"><!--Use Druid connection pool-->
        <property name="url" value="${jdbc.url}"/>
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="initialSize" value="${jdbc.initialSize}"/>
        <property name="maxActive" value="${jdbc.maxActive}"/>
    </bean>


    <!--to configure SqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/><!--Configure data sources-->
        <property name="configLocation" value="classpath:mybatis/mybatis-config.xml"/><!--add to mybatis to configure-->
        <!--Scan each Mapper Corresponding xml file-->
        <property name="mapperLocations" value="classpath*:com/feng/mapper/xml/*.xml"/>
    </bean>

    <!--Scan all Mapper-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <property name="basePackage" value="com.feng.mapper"/>
    </bean>

</beans>

First, configure our database data source, and then configure the SqlSessionFactory of Mybatis (used to produce sqlsessions and perform SQL operations through sqlsessions), but here the factory is managed by Spring, and finally scan all mappers. Therefore, Spring's integration of Mybatis means that Spring controls the SqlSessionFactory of Mybatis and lets Spring produce sqlsessions.

3.db.properties

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-tO5yKsN2-1633981381704)(C:\Users \ Feng Yongbin \ appdata \ roaming \ typora \ typora user images \ image-20211012025802172. PNG)]

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/doctor_order_db?serverTimezone=UTC&useSSL=false&allowPublicKeyRetrieval=true
jdbc.username=root
jdbc.password=fengbin
jdbc.initialSize=5
jdbc.maxActive=30

Now that our SSM project has been integrated, let's test it!

7, Testing

1. Test class construction:

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-WURitLi4-1633981381705)(C:\Users \ Feng Yongbin \ appdata \ roaming \ typora user images \ image-20211012030026397. PNG)]

2. Entity class

/*Each attribute of the entity class is consistent with the database field to facilitate the persistence management of mybatis*/
public class Doctor {

    private String doctor_id;
    private String doctor_password;
    private String doctor_name;
    private String doctor_position;
    private String doctor_department;
    private String doctor_sex;
    private Integer doctor_age;

    public Doctor() {
    }

    @Override
    public String toString() {
        return "Doctor{" +
                "doctor_id='" + doctor_id + '\'' +
                ", doctor_password='" + doctor_password + '\'' +
                ", doctor_name='" + doctor_name + '\'' +
                ", doctor_position='" + doctor_position + '\'' +
                ", doctor_department='" + doctor_department + '\'' +
                ", doctor_sex='" + doctor_sex + '\'' +
                ", doctor_age=" + doctor_age +
                '}';
    }

    public String getDoctor_id() {
        return doctor_id;
    }

    public void setDoctor_id(String doctor_id) {
        this.doctor_id = doctor_id;
    }

    public String getDoctor_password() {
        return doctor_password;
    }

    public void setDoctor_password(String doctor_password) {
        this.doctor_password = doctor_password;
    }

    public String getDoctor_name() {
        return doctor_name;
    }

    public void setDoctor_name(String doctor_name) {
        this.doctor_name = doctor_name;
    }

    public String getDoctor_position() {
        return doctor_position;
    }

    public void setDoctor_position(String doctor_position) {
        this.doctor_position = doctor_position;
    }

    public String getDoctor_department() {
        return doctor_department;
    }

    public void setDoctor_department(String doctor_department) {
        this.doctor_department = doctor_department;
    }

    public String getDoctor_sex() {
        return doctor_sex;
    }

    public void setDoctor_sex(String doctor_sex) {
        this.doctor_sex = doctor_sex;
    }

    public Integer getDoctor_age() {
        return doctor_age;
    }

    public void setDoctor_age(Integer doctor_age) {
        this.doctor_age = doctor_age;
    }

    public Doctor(String doctor_id, String doctor_password, String doctor_name, String doctor_position, String doctor_department, String doctor_sex, Integer doctor_age) {
        this.doctor_id = doctor_id;
        this.doctor_password = doctor_password;
        this.doctor_name = doctor_name;
        this.doctor_position = doctor_position;
        this.doctor_department = doctor_department;
        this.doctor_sex = doctor_sex;
        this.doctor_age = doctor_age;
    }
}

3. Persistent layer DoctorMapper interface

import com.feng.pojo.Doctor;import java.util.List;public interface DoctorMapper {    List<Doctor> queryAllDoctor(); //Query all doctor information}

4. Implementation of doctor mapper interface in persistence layer

Configuration of DoctorMapper.xml

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapper        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"        " http://mybatis.org/dtd/mybatis-3-mapper.dtd "> < mapper namespace =" com. Feng. Mapper. Doctormapper "> < select id =" queryalldoctor "resulttype =" doctor "> / * ID must be consistent with the method name in the interface * / select * from doctor_tb; < / Select > < / mapper >

5. Business layer DoctorService interface

import com.feng.pojo.Doctor;import java.util.List;public interface DoctorService {    List<Doctor> queryAllDoctor();}

6. Business layer DoctorService interface implementation class

import com.feng.mapper.DoctorMapper;import com.feng.pojo.Doctor;import com.feng.service.DoctorService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import java.util.List;@Servicepublic class DoctorServiceImpl implements DoctorService {    @Autowired    private DoctorMapper doctorMapper;    @Override    public List<Doctor> queryAllDoctor() {        return doctorMapper.queryAllDoctor();    }}

7. Presentation layer DoctorController

import com.feng.pojo.Doctor;import com.feng.service.DoctorService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.GetMapping;import java.util.List;@Controllerpublic class DoctorController {    @Autowired    private DoctorService doctorService;    @GetMapping("/")    public String sayHello(Model model) {        List<Doctor> list = doctorService.queryAllDoctor();        model.addAttribute("message",list);        return "hello";//Return to hello.jsp}}

8. Front end page hello.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="utf-8" %><html><head>    <title>Title</title></head><body>${message}</body></html>

9. Test results

Database data:

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-w4vHg3Ph-1633981381707)(C:\Users \ Feng Yongbin \ appdata \ roaming \ typora user images \ image-2021101203155799. PNG)]

jsp received data:

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-jaauEYVJ-1633981381707)(C:\Users \ Feng Yongbin \ appdata \ roaming \ typora user images \ image-20211012031744321. PNG)]

Posted by jordanwb on Mon, 11 Oct 2021 12:34:50 -0700