preface

This article continues the previous article “Spring+SpringMVC+Mybatis integrated development ideas and configuration details (A)”, the last article we reviewed the SSM related knowledge, tells the directory structure of an SSM project, and shows the SSM project architecture in the form of pictures. Now that the preparatory work is complete, it’s time to move on to the actual project construction. I’m going to give you the table of contents structure from last lecture, just in case you only read this chapter.

We use IDEA as a development tool, IDEA is really a very powerful development tool, the cost of learning is very low, did not turn over friends quickly turn over.

Set up the SSM environment using IDEA

Creating a New Maven Project

You can follow the following steps to set up the environment:

The rest is all the way down Next. Then we need to wait for IDEA to help us generate a basic WEB project.

Create a package and directory

After the IDEA generation project is complete, the initial directory looks like this:

Next, we create a new Java in Main and mark it as Sources Root. Then create a new package in Java, which should start with the same group name and end with the project name, so my package is com.roobtyan.ssm

Then you can create a new directory in the package, use the shortcut keys Ctrl+Shift+Alt+S to open the project configuration and find model, as shown below.

Then, right-click to create a new directory. After all the directories are created, they look like this:

In fact, all of our configuration files, except for SpringMVC, are in the resouces directory. In order for Spring and other initialization to find our configuration files, we need to mark this directory as the resources directory. Right click and go to Mark as Resources root. It ended up like this:

Writing Maven dependencies

Ok, now that we have the basic directory configured, all we need to do is import the jar files that the project depends on.

The jar file name role
spring-webmvc This is the JAR package for SpringMVC
spring-jdbc SpringJDBC, which we need to use, is a dependency
spring-test Spring’s unit test integration JAR is used during unit testing
spring-aspects Spring APO module JAR file
mybatis The core of the mybatis
mybatis-spring Mybatis -Spring integration adapter
c3p0 In order to ensure the efficiency of the project, the database connection pool is introduced, which can also be replaced by DBPC or Ali connection pool
mysql-connector-java Mysql connector, this version number depends on the version of mysql you install, because mine is 8, so the version may be a little different from yours
jstl Introduce JSTL support for JSP
javax.servlet-api Servlet support JAR files
junit Jar files required for unit testing, integrated with Spring-test
log4j Log JAR file, which, when configured, can print run time logs on the console or save to a file if necessary

Here is the configuration file: 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 > com. Roobtyan < / groupId > < artifactId > SSM < / artifactId > <version> 1.0-snapshot </version> <packaging> WAR </packaging> <name> SSM Maven Webapp</name> <! -- FIXME change it to the project's website --> <url>http://www.example.com</url> <properties> < project. Build. SourceEncoding > utf-8 < / project. Build. SourceEncoding > < maven.com piler. Source > 1.7 < / maven.com piler source > < maven.com piler target > 1.7 < / maven.com piler. Target > < / properties > < dependencies > <! -- SpringMVC --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> < version > 4.3.7. RELEASE < / version > < / dependency > <! -- Spring-Jdbc --> <! -- https://mvnrepository.com/artifact/org.springframework/spring-jdbc --> <dependency> < the groupId > org. Springframework < / groupId > < artifactId > spring - JDBC < / artifactId > < version > 4.3.7. RELEASE < / version > </dependency> <! --Spring-test --> <! -- https://mvnrepository.com/artifact/org.springframework/spring-test --> <dependency> < the groupId > org. Springframework < / groupId > < artifactId > spring - test < / artifactId > < version > 4.3.7. RELEASE < / version > </dependency> <! -- Spring faceted Programming --> <! -- https://mvnrepository.com/artifact/org.springframework/spring-aspects --> <dependency> < the groupId > org. Springframework < / groupId > < artifactId > spring - aspects < / artifactId > < version > 4.3.7. RELEASE < / version > </dependency> <! --MyBatis --> <! -- https://mvnrepository.com/artifact/org.mybatis/mybatis --> <dependency> <groupId>org.mybatis</groupId> The < artifactId > mybatis < / artifactId > < version > 3.4.2 < / version > < / dependency > <! MyBatis integration with Spring adaptation package --> <! -- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring --> <dependency> <groupId>org.mybatis</groupId> < artifactId > mybatis - spring < / artifactId > < version > 1.3.1 < / version > < / dependency > <! -- Database connection pool, driver --> <! -- https://mvnrepository.com/artifact/c3p0/c3p0 --> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> The < version > 0.9.1 < / version > < / dependency > <! -- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> < artifactId > mysql connector - Java < / artifactId > < version > 5.1.41 was < / version > < / dependency > <! -- (JSTL, servlet-API, junit) --> <! -- https://mvnrepository.com/artifact/jstl/jstl --> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> The < version > 1.2 < / version > < / dependency > <! -- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.0.1</version> <scope>provided</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> </dependencies> <build> <finalName>ssm</finalName> <pluginManagement><! -- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) --> <plugins> <plugin> < artifactId > maven - clean - plugin < / artifactId > < version > 3.0.0 < / version > < / plugin > <! -- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging --> Maven-resources-plugin </artifactId> <version>3.0.2</version> </plugin> <plugin> < artifactId > maven -- the compiler plugin < / artifactId > < version > 3.7.0 < / version > < / plugin > < plugin > < artifactId > maven - surefire plugin < / artifactId > < version > 2.20.1 < / version > < / plugin > < plugin > < artifactId > maven - war - the plugin < / artifactId > < version > 3.2.0 < / version > < / plugin > < plugin > < artifactId > maven -- install plugin < / artifactId > < version > 2.5.2 < / version > < / plugin > < plugin > Maven-deploy-plugin </artifactId> <version>2.8.2</version> </plugin> </plugins> </pluginManagement> </build> </project>Copy the code

Now that the dependencies are configured, it’s time to configure Spring and Mybatis, but before that, you need to do some additional configuration.

Additional configuration

Here we create two new files in Resources: jdbc.properties (database connection configuration file, the name of our test database is SSM) and log4j.properties (log4j logging configuration).

jdbc.properties

# connection url
jdbc.jdbcUrl=jdbc:mysql://localhost:3306/ssm
# drive
jdbc.driverClassName=com.mysql.jdbc.Driver
# username
jdbc.usernaem=root
# your password
jdbc.password=root
Copy the code

log4j.properties

# Global Logging Configuration
log4j.rootLogger=DEBUG, stdout
# Console output... (Console printing)
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
Copy the code

Configure the Spring

Create a new applicationContext.xml file in Resources. Since this is not easy to explain on its own, I will explain it as a comment in the configuration file. File name: applicationContext.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: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-4.3.xsd"> <! -- This tag is used to scan the package and the classes under the package. The classes that are scanned can use annotations, such as @service, etc. Once scanned, they will be put into the IOC container. Controller is not scanned because Controller is given to SpringMVC to scan. <context:component-scan base-package= context:component-scan base-package="com.roobtyan.ssm">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <! <context:property-placeholder location= -- add the JDBC configuration file you created earlier so that you can change the configuration flexibly without modifying the XML file"classpath:jdbc.properties"/ > <! Jdbc.properties allows you to easily use the configuration information, but only if you use itThe ${}This form of call --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driverClassName}"/>
        <property name="jdbcUrl" value="${jdbc.jdbcUrl}"/>
        <property name="user" value="${jdbc.usernaem}"/>
        <property name="password" value="${jdbc.password}"/> </bean> <! Mybatis integration development first to have a data source, so we will just configure the connection pool injection and then need mapper. XML file path, before learning Mybatis is manually created **. The good news is that Mybatis can help us to reverse generate the file and interface according to the database, which greatly facilitates our development. Finally, mybatis configuration file, we will see later --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>
        <property name="configLocation" value="classpath:mybatis-config.xml"/> </bean> <! Mybatis (mybatis, mybatis, mybatis, mybatis, mybatis, mybatis) Let's not understand this for now --> <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"/>
        <constructor-arg name="executorType" value="BATCH"/> </bean> <! Add the dao interface implementation to the IOC container. Since we have not configured the mapper interface file, we need to add the interface implementation file to the IOC, and can use the bean class= directly when injection"org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.roobtyan.ssm.dao"/> </bean> <! -- Transaction control, this is the configuration of Spring itself, if you do not understand, still recommend to learn the most important function of Spring: For example, when inserting a data error, the previous part of the information has been inserted into the database, it is necessary to delete the data from the database, not causing data pollution --> <bean ID ="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <! -- Control data source --> <property name="dataSource" ref="dataSource"/> </bean> <! <aop:config> <aop:config> Aop :pointcut id="txPoint" expression="execution(* com.roobtyan.ssm.service.. * (..) )"/ > <! Aop: Advisor advice-ref="txAdvice" pointcut-ref="txPoint"/> </aop:config> <! --> <tx:advice ID ="txAdvice">
        <tx:attributes>
            <tx:method name="*"/ > <! <tx:method name="get*" read-only="true"/> </tx:attributes> </tx:advice> <! Data Source mybatis integration transaction control transaction enhancement --> </beans>Copy the code

Configure Mybatis

We need to configure mybatis, comparatively speaking, the configuration of Mybatis is much simpler file name: mybatis-config.xml

<? 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>
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>

    <typeAliases>
        <package name="com.roobtyan.ssm.bean"/>
    </typeAliases>

</configuration>
Copy the code

It’s that simple.

Configuration for SpringMVC

The SpringMVC configuration file location is not in Resources, but in the web-INF file directory, we create a dispatcherservlet-servlet.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 http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <! --SpringMVC configuration file, including the control of the website jump logic, configuration --> <! <context:component-scan base-package= <context:component-scan base-package="com.roobtyan.ssm" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <! Configure the view parser to facilitate page return --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"/>
        <property name="suffix" value=".jsp"/> </bean> <! -- Two standard configurations that need to be configured anyway --> <! < MVC :default-servlet-handler/> <! Support for springMVC's more advanced features, JSR303 validation, quick Ajax... Map dynamic requests --> < MVC :annotation-driven/> </beans>Copy the code

Do you think you’re done configuring it? No, it doesn’t, and most importantly, in order for the SpringIOC container to start with the server at startup, it needs to be configured in the web.xml file, as well as some necessary filters, such as character encoding filters.

The web.xml configuration

<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"> <display-name>Archetype Created Web Application</display-name> <! -- Start the Spring container, and need to configure the Spring configuration file, <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <! -- characterEncodingFilter configuration --> <filter> <filter-name>characterEncodingFilter</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> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <! <filter-mapping> <filter-name>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <! Listener - configuration - > < listener > < listener - class > org. Springframework. Web. Context. ContextLoaderListener < / listener - class > < / listener > <! -- SpringMVC intercepts all requests so that they can be handed to SpringMVC instead of the way they were originally <servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>Copy the code

Finally, don’t forget to bring the configuration file into the environment. Open applicationContext.xml and you’ll see:

Then import, click Configure:

That’s all. I swear by my chastity that this configuration is sound and will work (as well as introducing mapper and other classes). If it doesn’t work, please feel free to ask me and voluntarily drop 1000 followers (EMM, I don’t have 1000 followers altogether …………).

A project

At the beginning and we said that there will be a project, the project is actually a shopping cart actual combat project, is based on the above configuration. If necessary, you can check out my article “shopping cart principle and implementation”, link: www.roobtyan.cn/index.php/2… (mobile phone access may have problems), there are also inside the public number, source code access also have, are in that article, I asked who else… If you do it to yourself, no problem, build a database, and then use Mybatis reverse generation tool to generate it, if you can’t find the method of reverse generation, you can ask me for the source code.

Well, the article is here, like my article can click a like, pay attention to my wechat public number: the highest authority bit stream