SSM (Spring+SpringMVC+MyBatis) framework is integrated by Spring, SpringMVC and MyBatis, and is often used as the framework of Web projects with relatively simple data sources.
Spring is a lightweight inversion of Control (IoC) and AOP oriented container framework. SpringMVC separates the roles of controller, model object, dispatcher, and handler object, which makes them easier to customize. MyBatis is an excellent persistence layer framework that supports ordinary SQL queries, stored procedures, and advanced mapping.
This article aims to quickly and in detail introduce intellij Idea to build the SSM framework through the process, especially suitable for the SSM framework is not very familiar with and interested in friends.
V Preparations
Preparing for development Environment
- Apache – tomcat 9.0 tomcat.apache.org/download-90…
- Apache – maven maven.apache.org/download.cg…
- MySQL www.mysql.com/downloads/
- The workbench dev.mysql.com/downloads/w…
- Java JDK www.oracle.com/technetwork…
- IntelliJ IDEAwww.jetbrains.com/idea/downlo…
For the configuration of such applications as above, there are many ready-made solutions on the Internet, and the basic operations are relatively simple, so I will not introduce them separately here. Once you’ve configured this, you can start building the framework.
V Creating a project
Click Next and fill in GroupId and ArtifactId.
Next, select the local Maven location
Go to Next and select the location where the project will be saved
Click Finish, and it will automatically generate the Maven skeleton and download the required JAR packages. The first creation may take a long time, but later it will be faster and wait for it to complete.
The project structure after creation is shown as follows:
Brief Introduction to project Structure:
- The.idea folder and helloWorld. Iml are some configuration files of IDEA, we do not need to care about, even if deleted, it will be ok, of course, delete, reopen the project, you have to reconfigure
- The SRC folder is where we put the project code
- Pom. XML is maven’s configuration file. We can add dependencies to any JAR we need, and Then Maven will help us drop it into the local repository
Create a new file structure for your project. Under Main, create a new Java for your Java files, under SRC, create a new test folder for your test files, under main, create a new Resources folder, right click, go to Make directory as, Select Resources root as shown below:
Next, continue to improve the project structure:
- In the Java folder of Main, right-click, go to Make Directory as, and select Sources root.
- In the Java folder of test, right-click, go to Make Directory as, and select Test Sources root
- In the Resources folder of Test, right-click, go to Make Directory as, and select Test Resources root
- SRC ->main-> Java create Package com and then create Package SpringMVC, which correspond to the groupid we started with
- Four new packages are created under the SpringMVC package. The Controller package is used to put the foreground URL mapping file, dao is used to put the interface file with the database, Entity is used to put the entity class file, and Service is used to put its defined interface
- Applicationcontext.xml is the Spring configuration file
- Sqlmap folder to put the entity and database mapping file
- Generatorconfig. XML and Generator.properties are configuration files for Mybatis
- Jdbc.properties is database-related information
- Log4j.properties is the log configuration file
- Create CSS, images and other files under WebApp to store front-end resources
- Web-inf new views file, JSP file in this
The directory structure is modified according to the above process as shown below:
V builds for springmvc
Configure Maven POM.xml to import jar packages
Pom.xml describes the project’s Maven coordinates, dependencies, rules developers need to follow, defect management systems, organizations and licenses, and all other project-related factors. It is a project-level configuration file.
<?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.springmvc</groupId>
<artifactId>hellobeijing</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>hellobeijing Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://maven.apache.org</url>
<properties>
<!-- spring版本号 -->
<spring.version>4.2.5.RELEASE</spring.version>
<!-- mybatis版本号 -->
<mybatis.version>3.2.4</mybatis.version>
<!-- log4j日志文件管理包版本 -->
<slf4j.version>1.6.6</slf4j.version>
<log4j.version>1.2.12</log4j.version>
</properties>
<dependencies>
<!-- spring核心包 -->
<!-- springframe start -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- springframe end -->
<!-- mybatis核心包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<!-- mybatis/spring包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.2</version>
</dependency>
<!-- mysql驱动包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.29</version>
</dependency>
<!-- junit测试包 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- jstl -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2.1-b03</version>
<scope>provided</scope>
</dependency>
<!-- servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<!-- json数据 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.7.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.7.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.7.1</version>
</dependency>
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
<!-- commons -->
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>commons-pool</groupId>
<artifactId>commons-pool</artifactId>
<version>1.5.6</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.8.3</version>
</dependency>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.9</version>
</dependency>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>jsr250-api</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>net.sf.ezmorph</groupId>
<artifactId>ezmorph</artifactId>
<version>1.0.6</version>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<!-- 日志文件管理包 -->
<!-- log start -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
<!--上传-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<!-- log end -->
</dependencies>
<build>
<finalName>helloworld</finalName>
<plugins>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.2</version>
<configuration>
<!--允许移动生成的文件-->
<verbose>true</verbose>
<!--允许覆盖生成的文件-->
<overwrite>true</overwrite>
</configuration>
</plugin>
</plugins>
</build>
</project>
Copy the code
View Code
If there is a red error, check that settings.xml is configured correctly. If there is no problem and it still displays a red error, move the cursor to that line, then type Alt + Enter, and select Update
My Settings. The XML
<? The XML version = "1.0" encoding = "utf-8"? > < Settings XMLNS = "http://maven.apache.org/SETTINGS/1.0.0" XMLNS: xsi = "http://www.w3.org/2001/XMLSchema-instance" Xsi: schemaLocation = "http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd" > <pluginGroups /> <proxies /> <servers /> <localRepository>D:/server/maven/repository</localRepository> <mirrors> <mirror> <id>alimaven</id> <name>aliyun maven</name> <url>http://maven.aliyun.com/nexus/content/groups/public/</url> <mirrorOf>central</mirrorOf> </mirror> </mirrors> <profiles> <profile> <id>nexus</id> <repositories> <repository> <id>nexus</id> <name>local private nexus</name> <url>http://maven.oschina.net/content/groups/public/</url> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>false</enabled> </snapshots> </repository> </repositories> <pluginRepositories> <pluginRepository> <id>nexus</id> <name>local private nexus</name> <url>http://maven.oschina.net/content/groups/public/</url> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>false</enabled> </snapshots> </pluginRepository> </pluginRepositories> </profile></profiles> </settings>Copy the code
View Code
Configure a JDBC properties
. Driver = com. Mysql. JDBC driver # mytest for my local database name url = JDBC: mysql: / / localhost: 3306 / mytest? UseUnicode =true&characterEncoding= utF-8 username=root # Enter your database password password=*********** # define the initial connection number initialSize=0 # define the maximum connection number MaxActive =20 minIdle=1 maxWait=60000Copy the code
View Code
Configuration applicationContext. XML
<? The 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:beans="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd "> <! - (1) : Scan all the classes in the com.SpringMVC package, <context:component-scan base-package=" com.springMVC "/> < MVC :annotation-driven /> <! -- Static resource access --> <! If you create a folder in WebApp and want to access static resources in it, < MVC :resources location="/images/" mapping="/images/**"/> mapping="/css/**"/> <mvc:resources location="/styles/" mapping="/styles/**"/> <mvc:resources location="/js/" mapping="/js/**"/> <! -- Configures the @Controller programming model <mvc:annotation-driven />--> <! - (2) : Enable Spring MVC annotations, To complete the request and annotate the POJO mapping - > < bean class = "org. Springframework. Web. Servlet. MVC. The annotation. AnnotationMethodHandlerAdapter" > <property name="messageConverters"> <list> <ref bean="mappingJacksonHttpMessageConverter"/> </list> </property> </bean> <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>application/json; charset=UTF-8</value> </list> </property> </bean> <! Configure the view resolver to map the controller's logical video to the real view. -- /WEB-INF/jsp/start.jsp --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <property name="prefix" value="/WEB-INF/views/" /> <property name="suffix" value=".jsp" /> </bean> <! -- Configure DBCP database connection pool --> <! -- <context:property-placeholder location="classpath:db.properties"/> --> <! -- Database configuration --> <bean id = "propertyConfigurer" class = "org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:jdbc.properties</value> </list> </property> </bean> <! - the database connection pool - > < bean id = "dataSource" class = "HTTP: / / org.apache.com mons. DBCP. BasicDataSource" destroy - method = "close" > < property name="driverClassName" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> <property name="initialSize" value="1"/> <property name="maxActive" value="100"/> <property name="maxIdle" value="5"/> <property name="maxWait" value="80000"/> </bean> <! - configuration transaction manager - > < bean id = "transactionManager" class = ". Org. Springframework. JDBC datasource. DataSourceTransactionManager "> <property name="dataSource" ref="dataSource" /> </bean> <! MVC :interceptors> <! Internationalized operation interceptors must be configured based on (request /Session/Cookie) --> <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" /> </mvc:interceptors> <! -- Define path<->view direct mapping without Controller --> <! -- <mvc:view-controller path="/" view-name="redirect:/" /> --> </beans>Copy the code
View Code
Configure log4j properties
Log4j is an open source project of Apache. By using Log4j, you can control the destination of log messages to the console, files, GUI components, even the socket server, NT event logger, UNIX Syslog daemon, etc. We can also control the output format of each log; By defining the level of each log message, we can more carefully control the log generation process. The most interesting thing is that these can be configured flexibly through a configuration file without the need to modify the application code.
Log4j. logger.toConsole=debug,stdout log4j.appender.stdout = org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target = System.out log4j.appender.stdout.layout = org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern =%d{yyyy-MM-dd HH\:mm\:ss} [%5p] - %c Catalina. home is the Tomcat directory. If there is no logs folder, an error will be reported. ## ## is more likely to place log files in Tomcat log directory ${catalina. Home} / logs/salesmanb2bError log # # # # absolute path, such as: e:/salesmanb2bError.log ## log4j.logger.daily=INFO,D log4j.appender.D = org.apache.log4j.DailyRollingFileAppender log4j.appender.D.File = ${catalina.home}/logs/helloworld/helloworld.log log4j.appender.D.Append = true log4j.appender.D.Threshold = INFO log4j.appender.D.layout = org.apache.log4j.PatternLayout log4j.appender.D.layout.ConversionPattern =%d{yyyy-MM-dd HH\:mm\:ss} [%5p] - %c -%F(%L) -%m%n ##log4j.logger.org.apache.ibatis=debug,stdout ##log4j.logger.java.sql=debug,stdoutCopy the code
View Code
Configure web. XML
<? The 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_3_0.xsd" version = "3.0" > <display-name>helloworld</display-name> <! <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> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <! Springmvc can accept all requests load-on-startup: indicates that the Servlet is initialized when the container is started; --> <servlet> <servlet-name>springServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <! [<servlet-name>]-servlet.xml; [<servlet-name>]-servlet.xml XML --> <init-param> <param-name>contextConfigLocation</param-name> <param-value> classpath:spring/applicationContext.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <! <servlet-mapping> <servlet-name>springServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <! - Spring configuration - > < listener > < listener - class > org. Springframework. Web. Context. ContextLoaderListener < / listener - class > </listener> <! <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.md</url-pattern> </servlet-mapping> <context-param> <param-name>contextConfigLocation</param-name> <param-value> classpath:spring/applicationContext.xml</param-value> </context-param> <! -- welcome page --> <welcome-file> <welcome-file>/ web-inf /index.jsp</welcome-file> </welcome-file> <! --404 error display page, configurable --> <! --<error-page>--> <! --<error-code>404</error-code>--> <! --<location>/WEB-INF/views/404.jsp</location>--> <! --</error-page>--> <! <session-timeout>600</session-timeout> </session-config> </web-app>Copy the code
View Code
Configure tomcat
At this point, the SpringMVC framework is basically set up, so let’s run and verify, which requires tomcat to be configured first
Here we choose the War Exploded mode, which is explained online as follows
War mode – Upload the WEB project to the server as a package. War Exploded mode – Upload the WEB project to the server using the location of the current folder
Change on Frame to Update Classes and Resources, which changes the JSP page to hot deploy without restarting the server, and then click OK to see the effect shown below
Click the green start button to start the project.
Start normally, at this point SpringMVC is fully configured.
vmybatis generato
Add the SqlSessionFactory configuration to the Spring file and add the following configuration to the applicationContext.xml file
<! - configuration session factory SqlSessionFactory - > < bean id = "SqlSessionFactory" class = "org. Mybatis. Spring. SqlSessionFactoryBean" > <! --> <property name="dataSource" /> <property name="mapperLocations" value="classpath:sqlmap/*Mapper.xml"/> <property name="typeAliasesPackage" value="com.springmvc.entity" /> </bean> <! Dynamic proxy objects generated by mapper's scanner are automatically registered in the Spring container. Bean is the id of the mapper class name (initials lowercase) -- - > < bean class = "org. Mybatis. Spring. Mapper. MapperScannerConfigurer" > <! <property name="basePackage" value="com.springmvc. Dao "/> <! - configuration sqlSessionFactoryBeanName - > < property name = "sqlSessionFactoryBeanName" value = "sqlSessionFactory" / > < / bean >Copy the code
View Code
You will also need to configure the Generatorconfig. XML file, below interview the mybatis- Generator configuration file
<? The 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="generator.properties"/> <classPathEntry Location = "D: \ server \ maven \ repository/mysql/mysql - connector - Java \ 5.1.29 \ mysql connector - Java - 5.1.29. Jar" / > < context id="context1"> <! <commentGenerator> < Property name="suppressAllComments" value="true" /><! --> <property name="suppressDate" value="true" /> <! </commentGenerator> <jdbcConnection driverClass="${driver}" connectionURL="${url}" userId="${username}" password="${password}" /> <! --> <javaTypeResolver> <! -- Whether to use bigDecimal, False automatically converts to the following types (Long, Integer, Short, Etc.) --> <property name="forceBigDecimals" value="false" /> </javaTypeResolver> <javaModelGenerator targetPackage="${modelPackage}" targetProject="${modelProject}" /> <sqlMapGenerator targetPackage="${sqlPackage}" targetProject="${sqlProject}" /> <javaClientGenerator targetPackage="${mapperPackage}" targetProject="${mapperProject}" type="XMLMAPPER" /> <! <table schema=" tableName="${table}" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"/> </context> </generatorConfiguration>Copy the code
View Code
Note that the location property of the classPathEntry node is the location of the mysql-connector-java.jar file. Maven has already automatically installed the jar package for us, because we need a driver to connect to the database. Find the path to the JAR package in External Libraries on the left.
Press Ctrl+ C and Ctrl+ V above to set the local path for the mysql JAR package.
Configuration of the generator. The properties
Mybatis – Generator is used when you use mybatis- Generator. Jdbc.properties is actually used at system runtime. These two information is similar, if the diagram is convenient, you can also merge the two into a file, write separately, good pluggable.
driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/mytest? UseUnicode =true&characterEncoding= UTF-8 username=root password=********* #entity package name and Java directory ModelPackage =com.springmvc. Entity modelProject= SRC /main/ Java MapperPackage = com.springmvC.dao mapperProject= SRC /main/ Java table=messageCopy the code
View Code
ModelPackage is the location where the entity class automatically generated when connecting to the database is saved, sqlPackage is the location where the XML mapping file is generated, mapperPackage is the location where the database interface is generated, and table is the name of the table in the database
Create table
To do this, we need to create a test table in the MyTest database.
use mytest;
CREATE TABLE `message` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`command` varchar(30) NOT NULL,
`description` varchar(30) NOT NULL,
`content` varchar(30) NOT NULL,
PRIMARY KEY (`id`)
)ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
select * from message;
Copy the code
View Code
The basic configuration of Mybatis is complete. Just double-click mybatis generator for Maven.
When “BUILD SUCCESS” is displayed in the log, it means that mybatis has been generated successfully. After SUCCESS, it will correspond to holy mapper. XML, DAO layer and Entity layer files.
(Update: There is no function bar on the right side. You can open it with view->tool buttons.)
V configuration junit
If you write a piece of code and want to verify that it is correct, you do not need to start Tomcat run or debug, then we can think of a test tool to verify that, here to configure junit tests. To test the new message interface, we need to add @repository tag to the Spring messagemapper file to indicate that it is a data access component, i.e. a DAO component
The diagram below:
To start the test, move the mouse over the MessageMapper (arrow direction) and press Alt + Enter on the keyboard to create Test
The diagram below:
Select the function method you want to test, click OK,
The diagram below:
Then the MessageMapperTest test file will be generated in the test directory, as shown below:
The test starts writing MessageMapperTest, writing the test code.
package com.springmvc.dao; import com.springmvc.entity.Message; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import static org.junit.Assert.*; /** * Created by toutou on 2018/5/10. */ public class MessageMapperTest { private ApplicationContext applicationContext; @Autowired private MessageMapper mapper; @before public void setUp() throws Exception {// Loads the Spring configuration file applicationContext = new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml"); / / import need to test the mapper = applicationContext. GetBean (MessageMapper. Class); } @After public void tearDown() throws Exception { } @Test public void insert() throws Exception { Message message = new Message(); Message. The setCommand (" eat "); Message. SetContent (" sleep "); Message. setDescription(" beanie "); int result = mapper.insert(message); System.out.println(result); assert (result == 1); }}Copy the code
View Code
OK, now that you’ve coded your test class, run Test, right click on the little green triangle, and run.
The diagram below:
Effect picture after operation:
OK, after the run, return 1, indicating that the run is successful.
So let’s go to the database and see if the eat, sleep, and play beans have been inserted into the database.
OK, we’re done.
V Source code address
Github.com/toutouge/ja…
V Blog Summary
This blog post is just an introduction to the SSM framework, originally intended to finish the SSM. However, I will try to cover a lot of details, which leads to a very long blog post and late night, so I will add an “on” section to the title. As for introducing the front and back end interaction of Spring MVC, I will leave it to the next section.
About the author: Focus on basic platform project development. If you have any questions or suggestions, please feel free to comment! Copyright notice: The copyright of this article belongs to the author and the blog garden, welcome to reprint, but without the consent of the author must retain this statement, and give the original text link in a prominent place on the page of the article. For the record: all comments and messages will be answered as soon as possible. You are welcome to correct your mistakes and make progress together. Or direct private message I support the blogger: if you think the article is helpful to you, you can click on the lower right corner of the article [recommendation]. Your encouragement is the author to adhere to the original and continuous writing of the biggest power! \