Learning notes: SSM framework integration steps

Three stages of SSM integration

Spring and spring MVC environment configuration
Integrated configuration of Spring and Mybatis
Other component configurations: declarative transactions, logs······

1, Spring and spring MVC environment configuration

1.1 relying on spring webmvc
Add the dependency package of spring MVC to the pom file

		<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.6.RELEASE</version>
        </dependency>

1.2 on the web Configure DispatcherServlet in XML file

    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:applicationContext*.xml</param-value>
        </init-param>
        <load-on-startup>0</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

1.3 enable spring MVC annotation mode
In ApplicationContext Configuring spring MVC annotation schema in XML

<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"
       xmlns:mv="http://www.springframework.org/schema/mvc"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:task="http://www.springframework.org/schema/task"
       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
            http://www.springframework.org/schema/tx
            http://www.springframework.org/schema/tx/spring-tx.xsd
            http://www.springframework.org/schema/task
            http://www.springframework.org/schema/task/spring-task.xsd">

    <context:component-scan base-package="com.imooc"/>
    <mvc:annotation-driven>
        <!--Solve the problem of Chinese garbled code in response output-->
        <mvc:message-converters>
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>text/html;charset=utf-8</value>
                        <value>application/json;charset=utf-8</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>
    <!--Exclude static resources and improve program processing efficiency-->
    <mvc:default-servlet-handler/>

1.4 configure request and response character set
To solve the character set encoding problem in the request, on the web Configure characterencoding filter in XML. This is a POST request for, and a get request is to change Tomcat's server XML file. After tomcat8, the default get request is encoded according to the character set of UTF-8, so there is no need to configure it manually

    <filter>
        <filter-name>characterFilter</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>characterFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

To solve the character set encoding problem in the response, see 1.3 enable the configuration content in the MVC: annotation driven tag in spring MVC annotation mode

1.5 configuring FreeMarker template engine
Add dependent packages to pom files
freemarker:FreeMarker template engine
Spring context support: spring support for FreeMarker template engine

        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.30</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>5.2.6.RELEASE</version>
        </dependency>

applicationContext. Configure FreeMarker template engine in XML file

    <bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
                <!--to configure ftl File storage address-->
        <property name="templateLoaderPath" value="/WEB-INF/ftl"></property>
        <property name="freemarkerSettings">
            <props>
                <!--this UTF-8 Is read ftl When the document is used, it is used UTF-8 To read ftl Contents of the document itself-->
                <prop key="defaultEncoding">UTF-8</prop>
            </props>
        </property>
    </bean>
    <!--this bean id "ViewResolve"r Fixed name, this is SpringMVC Mandatory provisions of the; This configuration determines which template engine is used to parse the data -->
    <bean id="ViewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
     	<!--This configuration means that the view parser combines the data with the template engine to produce a new view html Fragment, used when outputting to response utf-8 Character set encoding -->
        <property name="contentType" value="text/html;charset=utf-8"></property>
        <!--Configure template engine extension -->
        <property name="suffix" value=".ftl"></property>
    </bean>

1.6 configuring the Json serialization component
Add dependent packages to pom files
jackson core: the core of jackson
Jackson annotations: an annotation package that provides a series of annotations that can be used on entity classes to facilitate serialization and deserialization
Jackson databind: a data binding package that enables us to interact effectively with the data in spring MVC

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.12.5</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.12.5</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.12.5</version>
        </dependency>

2, Integrated configuration of Spring and Mybatis

2.1 the POM file relies on mybatis spring and driver

        <!--Mybatis integration Spring Introduce dependency-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.2.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.4</version>
        </dependency>
        <!--Mybatis And spring Integration components-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.3</version>
        </dependency>
        <!--mysql drive-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.25</version>
        </dependency>
        <!--Connection pool-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.14</version>
        </dependency>

2.2 applicationContext. Configuring data sources and connection pools in XML

    <!--Mybatis And Spring Consolidated configuration of-->
    <!--Configure data sources-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
        <property name="url"
                  value="jdbc:mysql://localhost:9999/imooc_reader?useSSL=false&amp;characterEncoding=UTF-8&amp;serverTimeZone=Asia/Shanghai&amp;allowPublicKeyRetrieval=true"></property>
        <property name="username" value="root"></property>
        <property name="password" value="root"></property>
        <property name="initialSize" value="5"></property>
        <property name="maxActive" value="30"></property>
    </bean>

2.3 applicationContext. Configure SqlSessionFactory in XML

    <!--SqlSessionFactoryBean Used to create a profile based on configuration information SqlSessionFactory,We no longer need to create our own code-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    	<!--data source -->
        <property name="dataSource" ref="dataSource"></property>
        <!--mapper File storage address -->
        <property name="mapperLocations" value="classpath:mappers/*.xml"></property>
        <!--Mybatis Profile address-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
    </bean>

2.4 applicationContext. Configuring Mapper scanner in XML

    <!--to configure Mapper Scanner,For scanning com.imooc.reader.mapper All under the package mapper Interface, and according to the corresponding xml Documents( mapper File) automatically generate implementation classes-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.imooc.reader.mapper"/>
    </bean>

2.5 create mybatis config xml

<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
        <!--Turn on hump switching-->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
</configuration>

3, Other component configurations

3.1 integrated JUint unit test
Add dependent package in pom file

        <!--Unit test dependency-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.2.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>

Comments need to be added to the test file to facilitate initialization

@RunWith(SpringJUnit4ClassRunner.class) //This annotation indicates that JUnit will automatically initialize the IOC container at run time
@ContextConfiguration(locations = {"classpath:applicationContext.xml"}) //This annotation indicates where the configuration file is
public class TestServiceTest {
    @Resource
    private TestService testService;

    @Test
    public void batchImport() {
        testService.batchImport();
    }
}

3.2 configuring logback log output
Introducing related dependencies into pom files

        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.3</version>
        </dependency>

Create logback XML and complete the relevant configuration

<configuration>
    <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <pattern> %d{YYYY-MM-dd HH:mm:ss} %-5level [%thread] %logger{30} - %msg%n</pattern>
            <charset>utf-8</charset>
        </encoder>
    </appender>
    <root level="debugger">
        <appender-ref ref="console"></appender-ref>
    </root>
    <!--Save the log in a file in days-->
    <appender name="accessHistoryLog" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>d:/logs/history.%d.log</fileNamePattern>
        </rollingPolicy>
        <encoder>
            <pattern>[%thread] %d %level %logger{30} - %msg%n</pattern>
        </encoder>
    </appender>
    <logger name="com.imooc.reader.interceptor.LoginInterceptor" level="info" additivity="false">
        <appender-ref ref="accessHistoryLog"/>
    </logger>
</configuration>
</configuration>

3.3 declarative transaction configuration
In ApplicationContext Configuration in XML

    <!--Declarative transaction configuration-->
    <!--transacationManager Controls the opening, commit, and rollback of transactions-->
    <bean id="transacationManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    	<!--Configure data sources -->
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!--Declarative transactions with annotation mode enabled-->
    <tx:annotation-driven transaction-manager="transacationManager"/>

As long as the @ Transactional annotation is added to the method, it means that declarative transactions are enabled

Keywords: Java Mybatis Spring Spring MVC

Added by morrisoner on Fri, 10 Dec 2021 18:25:46 +0200