instructions

This article introduces how to set up an SSM project through IDEA in detail with pictures and pictures, which is very friendly to those who are not familiar with IDEA or have not used IDEA before. The project has been uploaded to the lot, address: https://github.com/gitlxp1101/ssm_demo.git

1. Create a Web project with IDEA

1.1 Create a project in the Start screen

Open IDEA and click the option circled in the red box in the picture below



1.2 Create a new project from the currently opened project page

If you open IDEA, you can directly enter the last closed project. You can choose:
File->New->Project



1.3 choose the archetype

Select maven,
Check Create from archetype and go maven-archetype-web-app“, and click “Next”. As shown below:



1.4 Name the project

Give GroupId and ArtifactId proper names. Next, select the Maven configuration and project location. You can configure it yourself, and then click “Next” until the project is created. As shown below:



1.5 Create a project and directory structure




2 Creating a Directory

Careful friends may find that the project created in this way lacks a directory to store classes and resources, so we need to create our own.

2.1 Creating a directory for Storing Java code: Java

Right-click main -> New -> Directory and name the New Directory “Java”.





2.2 Have IDEA identify the directory where the class is stored

A newly created “Java” directory is not recognized as a class directory and needs to be marked to be recognized. Specific operations are as follows:
Right-click the main Directory -> New -> Mark Directory as -> Sources Root



2.3 Directory Color Change

If you are careful, you will notice that the color of the “Java” directory has changed from grey to blue. Here I have created a directory called Resources. You can compare:



2.4 Directory Labels

Here’S a quick explanation of what the Mark Directory as option does:
  1. Sources Root: Used to store Java code
  2. Test Sources Root: Stores Java Test code
  3. ReSources Root: The folder used to develop storage resources for the project, such as configuration files, classpath level, and common code that requires certain resources, such as resources marked as Resources Root, This directory has an applicationContext.xml. When writing the path in your code, you can say classpath: ApplicationContext.xml
  4. Test ReSources Root: folder used for project Test development storage ReSources



2.5 Creating a Resource Directory resources

Step is basically the same as the previous step, you need to mark the Resources directory as: Resources Root



2.6 Testing Directories

2.6.1 Create a test directory in the SRC directory, which is the same as the main directory


2.6.2 Create “Java” and “Resources” directories in the “test” directory and mark them as “Test Sources Root” and “Test Resources Root” (refer to the previous section for details, the steps are similar)


2.7 Overall project directory structure





3 Introducing Maven dependencies

I’ve put all the dependencies I need down here

<? 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. Example < / groupId > < artifactId > ssm_demo < / artifactId > <version> 1.0-snapshot </version> <packaging>war</packaging> <name>ssm_demo 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.compiler.source>1.8</maven.compiler.source>    <maven.compiler.target>1.8</maven.compiler.target>    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>    <maven.compiler.encoding>UTF-8</maven.compiler.encoding>    <org.springframework.version>4.0.0.RELEASE</org.springframework.version>    <org.mybatis.version>3.4.1</org.mybatis.version>    <org.mybatis.spring.version>1.3.0</org.mybatis.spring.version>  </properties>  <dependencies>    <dependency>      <groupId>org.apache.tomcat</groupId>      <artifactId>tomcat-servlet-api</artifactId>      <version>7.0.64</version>    </dependency>    <dependency>      <groupId>org.springframework</groupId>      <artifactId>spring-webmvc</artifactId>      <version>${org.springframework.version}</version>    </dependency>    <dependency>      <groupId>org.springframework</groupId>      <artifactId>spring-oxm</artifactId>      <version>${org.springframework.version}</version>    </dependency>    <dependency>      <groupId>org.springframework</groupId>      <artifactId>spring-jdbc</artifactId>      <version>${org.springframework.version}</version>    </dependency>    <dependency>      <groupId>org.springframework</groupId>      <artifactId>spring-tx</artifactId>      <version>${org.springframework.version}</version>    </dependency>    <dependency>      <groupId>org.springframework</groupId>      <artifactId>spring-test</artifactId>      <version>${org.springframework.version}</version>    </dependency>    <dependency>      <groupId>org.aspectj</groupId>      <artifactId>aspectjweaver</artifactId>      <version>1.7.3</version>    </dependency>    <dependency>      <groupId>org.mybatis</groupId>      <artifactId>mybatis-spring</artifactId>      <version>${org.mybatis.spring.version}</version>    </dependency>    <dependency>      <groupId>org.mybatis</groupId>      <artifactId>mybatis</artifactId>      <version>${org.mybatis.version}</version>    </dependency>    <!-- mybatis pager -->    <dependency>      <groupId>com.github.pagehelper</groupId>      <artifactId>pagehelper</artifactId>      <version>4.1.0</version>    </dependency>    <!--集成druid连接池-->    <dependency>      <groupId>com.alibaba</groupId>      <artifactId>druid-spring-boot-starter</artifactId>      <version>1.1.10</version>    </dependency>    <!-- MyBatis 生成器 -->    <dependency>      <groupId>org.mybatis.generator</groupId>      <artifactId>mybatis-generator-core</artifactId>      <version>1.3.7</version>    </dependency>    <dependency>      <groupId>mysql</groupId>      <artifactId>mysql-connector-java</artifactId>      <version>5.1.6</version>    </dependency>    <dependency>      <groupId>org.aspectj</groupId>      <artifactId>aspectjrt</artifactId>      <version>1.6.11</version>    </dependency>    <dependency>      <groupId>org.codehaus.jackson</groupId>      <artifactId>jackson-mapper-asl</artifactId>      <version>1.9.12</version>    </dependency>    <dependency>      <groupId>ch.qos.logback</groupId>      <artifactId>logback-classic</artifactId>      <version>1.1.2</version>      <scope>compile</scope>    </dependency>    <dependency>      <groupId>ch.qos.logback</groupId>      <artifactId>logback-core</artifactId>      <version>1.1.2</version>      <scope>compile</scope>    </dependency>    <dependency>      <groupId>com.google.guava</groupId>      <artifactId>guava</artifactId>      <version>20.0</version>    </dependency>    <dependency>      <groupId>org.apache.commons</groupId>      <artifactId>commons-lang3</artifactId>      <version>3.5</version>    </dependency>    <dependency>      <groupId>commons-collections</groupId>      <artifactId>commons-collections</artifactId>      <version>3.2.1</version>    </dependency>    <dependency>      <groupId>junit</groupId>      <artifactId>junit</artifactId>      <version>4.12</version>      <!--<scope>test</scope>-->    </dependency>    <dependency>      <groupId>joda-time</groupId>      <artifactId>joda-time</artifactId>      <version>2.3</version>    </dependency>    <!-- id加密解密 -->    <dependency>      <groupId>org.hashids</groupId>      <artifactId>hashids</artifactId>      <version>1.0.1</version>    </dependency>    <!-- file upload -->    <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->    <dependency>      <groupId>commons-fileupload</groupId>      <artifactId>commons-fileupload</artifactId>      <version>1.2.2</version>    </dependency>    <dependency>      <groupId>commons-io</groupId>      <artifactId>commons-io</artifactId>      <version>2.0.1</version>    </dependency>  </dependencies>  <build>    <finalName>ssm_demo</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.1.0</version>        </plugin>        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->        <plugin>          <artifactId>maven-resources-plugin</artifactId>          <version>3.0.2</version>        </plugin>        <plugin>          <artifactId>maven-compiler-plugin</artifactId>          <version>3.8.0</version>        </plugin>        <plugin>          <artifactId>maven-surefire-plugin</artifactId>          <version>2.22.1</version>        </plugin>        <plugin>          <artifactId>maven-war-plugin</artifactId>          <version>3.2.2</version>        </plugin>        <plugin>          <artifactId>maven-install-plugin</artifactId>          <version>2.5.2</version>        </plugin>        <plugin>          <artifactId>maven-deploy-plugin</artifactId>          <version>2.8.2</version>        </plugin>      </plugins>    </pluginManagement>  </build></project>Copy the code




4 The container loads the Spring configuration file

4.1 the listener

Configure a listener in web.xml to load the Spring configuration file after the Tomcat container starts. I named the Spring configuration file applicationContext.xml in the Resources directory.



4.2 configuration applicationContext. XML

Here are two common tags





2 package scanning


Yes, the container can be started to scan for all annotations of the package “com.example” and its subpackages



2 aspects


Weave into the @AspectJ section by configuration



4.3 ApplicationContext.xml is fully configured

<? 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:aop="http://www.springframework.org/schema/aop"        xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"        xmlns:context="http://www.springframework.org/schema/context"        xsi:schemaLocation=" http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">      <context:component-scan base-package="com.example" annotation-config="true"/>      <aop:aspectj-autoproxy/>    </beans>Copy the code


5 The container loads the SpringMVC configuration file

5.1 Configuring Interception Rules in web. XML



5.2 SpringMVC Configuration File

If you configure “interceptor name-servlet.xml” in the same directory as web.xml, SpringMVC will automatically scan the file. If I configure the interceptor name as “dispatcher”, the dispatcher-servlet.xml in the same directory as web.xml will be scanned.

5.3 Dispatcher-servlet. XML is completely configured and explained in the configuration.

<? 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:p="http://www.springframework.org/schema/p"        xmlns:context="http://www.springframework.org/schema/context"        xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop"        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"> <! -- Only scan comments under com.example.controller --> <! --use-default-filters=false: do not use default scan --> <context:component-scan base-package="com.example.controller" annotation-config="true" use-default-filters="false"> <! -- Scan only the bean of Controller --> <context:include-filtertype="annotation" expression="org.springframework.stereotype.Controller"></context:include-filter> </context:component-scan> <! < MVC :annotation-driven> < MVC :message-converters> <bean class="org.springframework.http.converter.StringHttpMessageConverter">                 <property name="supportedMediaTypes"> <list> <value>text/plain; charset=UTF-8</value> <value>text/html; charset=UTF-8</value> </list> </property> </bean> <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">                 <property name="supportedMediaTypes"> <list> <value>application/json; charset=UTF-8</value> </list> </property> </bean> </mvc:message-converters> </mvc:annotation-driven> <! -- file upload --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">         <property name="maxUploadSize" value="10485760"/ > <! -- 10m --> <property name="maxInMemorySize" value="4096" />         <property name="defaultEncoding" value="UTF-8"></property>     </bean>   </beans>Copy the code

5.4 Complete configuration of 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"          id="WebApp_ID" version="2.5"> <display-name>Archetype Created Web Application</display-name> <! -- String filter --> <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> <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class> </listener> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value> classpath:applicationContext.xml </param-value> </context-param> <! -- Configure springMVC interception rules if configured in the web.xml sibling directory"Interceptor -servlet.xml", SpringMVC automatically scans the file. -- > <! If THE interceptor name is dispatcher, > <servlet> <servlet-name>dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>Copy the code

5.5 Current project directory structure



5.6 summary

Now that we’ve completed the Spring+SpringMVC integration, let’s test for any problems


5.6.1 Configure the project in IDEA for startup


5.6.1.1 Click “Edit Configurations” at the top of IDEA as shown in the figure



5.6.1.2 Refer to the following figure



5.6.1.3 Click to see the configuration page as shown below



5.6.1.4 Name the project sSM_demo
5.6.1.5 Here can also change the boot port number, I will not change here, use the default 8080
The artifact is missing and the next step is to configure the artifact.



5.6.1.7 configure an artifact
Add an artifact as shown, remembering to choose the version with the exploded end, and explain why later.







5.6.1.8 heat release
To put it simply, when a program is running with debug, after modifying code, the program can see the modified result without restarting the project. Let’s go back to the original configuration page and configure as shown in the following figure. Then click OK. complete



5.6.1.9 run
Once configured, you can see the following results. The store’s green triangle can launch the project, which can be seen in the browser below the results.







So let’s write a test Controller here and look at it in the browser.





6. Integrating Mybatis

6.1 Mybatis generator

Generate model, Mapper interface and mapper.xml using Mybatis Generator

6.1.1 Create a com.example. MBG package to store the code that generates these files
6.1.2 the Generator. Java

package com.example.mbg; import org.mybatis.generator.api.MyBatisGenerator; import org.mybatis.generator.config.Configuration; import org.mybatis.generator.config.xml.ConfigurationParser; import org.mybatis.generator.internal.DefaultShellCallback; import java.io.InputStream; import java.util.ArrayList; import java.util.List; Public class Generator {public static void main(String[] args) {public static void main(String[] args); Throws Exception {//MBG warning message List Warnings = new ArrayList(); Boolean overwrite = when generated code is duplicatedtrue; / / read our MBG configuration file InputStream is = Generator. Class. GetResourceAsStream ("/generatorConfig.xml"); ConfigurationParser cp = new ConfigurationParser(warnings); Configuration config = cp.parseConfiguration(is); is.close(); DefaultShellCallback callback = new DefaultShellCallback(overwrite); // Create MBG MyBatisGenerator MyBatisGenerator = new MyBatisGenerator(config, callback, warnings); / / execution code generation myBatisGenerator. Generate (null). // Displays a warning messagefor(String warning : warnings) { System.out.println(warning); }}}Copy the code

Also 6.1.3 configuration generatorConfig. XML
As you can see in the previous section, we need a generatorConfig.xml file (created in the Resources directory) to configure the generated information. I have put the specific content below, notes are also written inside, you can take a look.

<? xml version="1.0" encoding="UTF-8"? > <! DOCTYPE generatorConfiguration PUBLIC"-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"         "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">  <generatorConfiguration>     <properties resource="datasource.properties"/>     <context id="MySqlContext" targetRuntime="MyBatis3" defaultModelType="flat">         <property name="beginningDelimiter" value="`"/>         <property name="endingDelimiter" value="`"/>         <property name="javaFileEncoding" value="UTF-8"/ > <! Generate serialization methods for the model --> <plugintype="org.mybatis.generator.plugins.SerializablePlugin"/ > <! Create a toString method for the generated Java model --> <plugintype="org.mybatis.generator.plugins.ToStringPlugin"/ > <! Mapper.xml is generated to override the original file --> <plugintype="org.mybatis.generator.plugins.UnmergeableXmlMappersPlugin"/ > <! --> <jdbcConnection driverClass="${jdbc.driverClass}"                         connectionURL="${jdbc.connectionURL}"                         userId="${jdbc.userId}"                         password="${jdbc.password}"> <! Mysql > <property name="nullCatalogMeansCurrent" value="true"/> </jdbcConnection> <! JavaModelGenerator targetPackage= <javaModelGenerator targetPackage="com.example.domain" targetProject="./src/main/java"/ > <! -- specify the path to generate mapper. XML --> <sqlMapGenerator targetPackage="mapper" targetProject="./src/main/resources"/ > <! -- Specify the path to generate mapper interface --> <javaClientGeneratortype="XMLMAPPER" targetPackage="com.example.dao"                              targetProject="./src/main/java"/ > <! <table tableName= <table tableName= <table tableName= <table tableName="%">             <generatedKey column="id" sqlStatement="MySql" identity="true"/>         </table>     </context> </generatorConfiguration>Copy the code

6.1.4 datasource. The properties
Generatorconfig. XML requires connection information for the database, which I put in datasource. Properties (created under resources). The following shows the contents of generator.properties, which you can modify to suit your needs

jdbc.driverClass=com.mysql.jdbc.Driver
Select the database to configurejdbc.connectionURL=jdbc:mysql://localhost:3306/spring? useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
Database user name
jdbc.userId=root
# database password
jdbc.password=123456Copy the code

6.2 integration of Mybatis

6.2.1 Create an applicationContext-datasource. XML file in the Resources directory to configure the database and Mybatis.
applicationContext-datasource.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:aop="http://www.springframework.org/schema/aop"        xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"        xmlns:context="http://www.springframework.org/schema/context"        xsi:schemaLocation=" http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <! -- used to load properties files --> <bean id="propertyConfigurer"           class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">         <property name="order" value="2"/>         <property name="ignoreUnresolvablePlaceholders" value="true"/>         <property name="locations">             <list>                 <value>classpath:datasource.properties</value>             </list>         </property>         <property name="fileEncoding" value="utf-8"/> </bean> <! Data source configuration based on Druid database link pool --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <! -- Basic properties driverClassName, URL, user, password --> <property name="driverClassName" value="com.mysql.jdbc.Driver" />         <property name="url" value="${jdbc.connectionURL}" />         <property name="username" value="${jdbc.userId}" />         <property name="password" value="${jdbc.password}"/ > <! -- Configure initialization size, min, Max --> <! InitialSize, minIdle, maxActive --> <property name="initialSize" value="2" />         <property name="minIdle" value="2" />         <property name="maxActive" value="30" />         <property name="testWhileIdle" value="false"/ > <! -- Set the timeout for waiting to get connections --> <property name="maxWait" value="5000"/ > <! -- Set the minimum time for a connection to live in the pool, in milliseconds --> <property name="minEvictableIdleTimeMillis" value="30000"/ > <! -- Configure how often to check for idle connections to close, in milliseconds --> <property name="timeBetweenEvictionRunsMillis" value="60000"/ > <! -- Decryption password must be configured --> <property name="filters" value="config" />         <property name="connectionProperties" value="config.decrypt=false"/> </bean> <! Mybatis SqlSessionFactoryBean--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">         <property name="dataSource" ref="dataSource"/>         <property name="mapperLocations" value="classpath*:mapper/*Mapper.xml"></property>     </bean>           <bean name="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">         <property name="basePackage" value="com.example.dao"/> </bean> <! <tx:annotation-driven Transaction-Manager = < TX: Annotation-driven Transaction-manager ="transactionManager" proxy-target-class="true"/ > <! -- Transaction management --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">         <property name="dataSource" ref="dataSource"/>         <property name="rollbackOnCommitFailure" value="true"/>     </bean>   </beans>Copy the code

6.2.2 Introduce applicationContext-datasource. XML in ApplicationContext. XML



6.2.3 test
6.2.3.1 Add the following to the test class TestController and start Tomcat



6.2.3.2 Enter the following information to view the result



6.2.3.3 I put the database file in the resources/db directory, and friends who need it can add it to their own database





6.3 Overall project structure