SSM integration (they are copied and will not be configured by themselves after reading them for half a month. Here are the problems encountered in their configuration)

Posted by Revlet on Sat, 05 Mar 2022 10:06:06 +0100

Construction steps

Here, the database connection pool, springmvc, mybatis and service are created separately, and then import is integrated into ApplicationContext xml

  1. New project
  2. Guide Package
  3. Create external file dB properties
  4. Configure spring Dao xml:
    a. Associated database file
    b. Configure database source
    c. Configure bean sqlSessionFactory
    d. Scan Dao package, dynamically implement Dao interface injection into spring container
  5. Configure log4j The properties log is introduced into the following mybatis config xml
  6. Configure mybatis config xml
    a. Set the log (there is no need to import the file, which should be recognized automatically when necessary. Here must be log4j.properties. Try not to change the name)
    b. Set alias
    c. Binding interface (each entity class corresponds to a mapper.xml file, which can be bound by scanning all * mapper.xml through package. You can also bind one by one using < mapper resource, which is more troublesome.)
  7. Configure spring service xml
    a. Scan Service related beans (scan Service, which should mean supporting annotation to make @ Service available)
    b. Configure the transaction manager (the transaction manager is made by spring and I haven't used it. I think it is the transaction involved in the implementation of the service layer)
  8. Configure spring MVC xml
    a. Enable annotation driven
    b. Static resource filtering (css, js...)
    c. Configure view parser
    d. Scan the Controller (scan the beans related to the web, which is equivalent to registering two beans, DefaultAnnotationHandlerMapping and AnnotationMethodHandlerAdapter, and configuring some messageconverter s. That is, solve the premise configuration of @ Controller annotation.)
  9. web.xml
    a. Configure DispatcherServlet and load configuration file
    b. Set the site name, generally '/'
    c. Set coding to solve the problem of jsp garbled code

2. Guide bag POM xml

<?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>org.example</groupId>
    <artifactId>ssmbuild</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <!--Junit-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <!--log4j -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <!--Database driven-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <!-- Database connection pool -->
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.10</version>
        </dependency>

        <!--Servlet - JSP -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <!--Mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.2</version>
        </dependency>

        <!--Spring-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>
    </dependencies>

    <!--Resource filtering-->
    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>

</project>

3,db.properties

prop.driver=com.mysql.jdbc.Driver
prop.url=jdbc:mysql://localhost:3306/test?useSSL=true&useUnicode=true&characterEncoding=UTF-8
prop.username=root
prop.password=sz@mysql

4,spring-dao.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
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd">

    <!-- Configuration integration mybatis -->
    <!-- 1.Associated database file -->
    <context:property-placeholder location="classpath:db.properties"/>

    <!-- 2.Database connection pool -->
    <!--Database connection pool
        dbcp Semi automatic operation cannot be connected automatically
        c3p0 Automatic operation (automatically load the configuration file and set it into the object)
    -->

    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <!-- Configure connection pool properties -->
        <property name="driverClass" value="${prop.driver}"/>
        <property name="jdbcUrl" value="${prop.url}"/>
        <property name="user" value="${prop.username}"/>
        <property name="password" value="${prop.password}"/>

        <!-- c3p0 Private properties of connection pool -->
        <property name="maxPoolSize" value="30"/>
        <property name="minPoolSize" value="10"/>
        <!-- Not automatically after closing the connection commit -->
        <property name="autoCommitOnClose" value="false"/>
        <!-- Get connection timeout -->
        <property name="checkoutTimeout" value="10000"/>
        <!-- Number of retries when getting connection failed -->
        <property name="acquireRetryAttempts" value="2"/>
    </bean>

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


    <!-- 3.to configure SqlSessionFactory object -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- Inject database connection pool -->
        <property name="dataSource" ref="dataSource"/>
        <!-- to configure MyBaties Global profile:mybatis-config.xml -->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
    </bean>

    <!-- 4.Configure scan Dao Interface package, dynamic implementation Dao Interface injection into spring In container -->
    <!--Explanation: https://www.cnblogs.com/jpfss/p/7799806.html-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- injection sqlSessionFactory -->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <!-- Given the need to scan Dao Interface package -->
        <property name="basePackage" value="com.ssm.dao"/>
    </bean>
</beans>

5,log4j.properties

#Output the log information with the level of DEBUG to the two destinations of console and file. The definitions of console and file are in the following code
log4j.rootLogger=DEBUG,console,file

#Relevant settings of console output
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.Target = System.out
log4j.appender.console.Threshold=DEBUG
log4j.appender.console.layout = org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%c]-%m%n

#Relevant settings for file output
log4j.appender.file = org.apache.log4j.RollingFileAppender
log4j.appender.file.File=D:\\log\\mybatis.log
log4j.appender.file.MaxFileSize=10mb
log4j.appender.file.Threshold=DEBUG
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%p][%d{yy-MM-dd}][%c]%m%n

#Log output level
log4j.logger.org.mybatis=DEBUG
log4j.logger.java.sql=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG

6,mybatis-config.xml

(I tried to bind the second interface, but I couldn't use it. I should have made a mistake)

<?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>
<!--
    properties
    settings
    typeAliases
    typeHandlers
    objectFactory
    objectWrapperFactory
    reflectorFactory
    plugins
    environments
    databaseIdProvider
    mappers
-->
    <!--journal-->
    <settings>
        <setting name="logImpl" value="LOG4J"/>
    </settings>
    <!--Set an alias so that mapper.xml You don't have to specify the full pathname of the entity-->
    <typeAliases>
        <package name="com.ssm.pojo"/>
    </typeAliases>
    <mappers>
        <!--Bind interface to configuration-->
        <!--Method 1-->
        <!--<mapper resource="com/mybatis/dao/UserMapper.xml"/>-->
        <!--Method 2-->
        <!--<mapper resource="com/mybatis/dao/*.xml"/>-->
        <!--Method 3-->
        <package name="com.ssm.dao"/>
    </mappers>
</configuration>

7,spring-service.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
   http://www.springframework.org/schema/beans/spring-beans.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context.xsd">
    <!-- scanning service dependent bean -->
    <context:component-scan base-package="com.ssm.service" />
    <!-- Configure transaction manager -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- Inject database connection pool -->
        <property name="dataSource" ref="dataSource" />
    </bean>
</beans>

8,spring-mvc.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"
       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
   https://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!-- to configure SpringMVC -->
    <!-- 1.open SpringMVC Annotation driven -->
    <mvc:annotation-driven />
    <!-- 2.Static resource default servlet to configure-->
    <mvc:default-servlet-handler/>
    <!-- 3.to configure jsp display ViewResolver view resolver  -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
    <!--
    4.scanning web dependent bean
    It's equivalent to registering DefaultAnnotationHandlerMapping and AnnotationMethodHandlerAdapter Two bean,
    Configure some messageconverter.That's it@Controller Use premise configuration of annotation.
    -->
    <context:component-scan base-package="com.ssm.controller" />
</beans>

9,web.xml

<?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_4_0.xsd"
         version="4.0">
    <!--DispatcherServlet-->
    <servlet>
        <servlet-name>DispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <!--Be careful:What we load here is the total configuration file, which was damaged here before!-->
            <param-value>classpath:applicationContext.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>

    <!--encodingFilter-->
    <filter>
        <filter-name>encodingFilter</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>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!--Session Expiration time-->
    <session-config>
        <session-timeout>15</session-timeout>
    </session-config>
</web-app>

Problems encountered

1. Coding problem

New DB Properties defaults to GBK format, which causes all Chinese comments to be unrecognized when the project is opened
bug::: invalid byte 2 of UTF-8 sequence
Solution: change file -- > settings -- > editor -- > file encodings to UTF-8
Reference here

1. Database configuration problem

Error: "Access denies for user"“ administrator@localhost ” require password=yes
It's basically wrong to report others root@localhost , I don't know why. It's probably a name conflict
Error reason:
db.properties
...
username=...
Change to
prop.username
Or use "root" instead of ${username}

Topics: Java Mybatis Spring Spring MVC