SSM (Spring, SpringMVC and Mybatis) has been used for a long time, there are no technical difficulties in the project, based on the existing technology can achieve the desired function, of course there is certainly a lot of improvement. I did not record the SSM integration process before, but this time I just rebuilt it based on my own small project, and it is better than the project. I did not record the process and methods of solving problems in time. I will sort them out and share them when I meet them in my own small projects. This time, first talk about the three framework integration process. Personally, I don’t think it’s difficult to use a framework. The key is to understand its ideas, which are very helpful for us to improve our programming skills. However, if you don’t know how to use, talking about ideas will become an armchair strategist!! First technology, then thought. Practice is the mother of wisdom.

1. Let’s start with a basic concept

Spring

Spring is an open source framework. Spring is a lightweight Java development framework that started in 2003. Derived from some of the concepts and prototypes elaborated by Rod Johnson in his book Expert One-On-One J2EE Development and Design. It was created to address the complexity of enterprise application development. Spring uses basic Javabeans to do things that were previously only possible with EJBs. However, Spring’s use is not limited to server-side development. Any Java application can benefit from Spring in terms of simplicity, testability, and loose coupling. In simple terms, Spring is a lightweight Inversion of Control (IoC) and AOP oriented container framework.

SpringMVC

Spring MVC is a successor to the Spring Framework and has been integrated into Spring Web Flow. Spring MVC separates the roles of controller, model object, dispatcher, and handler object, which makes them easier to customize.

MyBatis

MyBatis is an open source project of Apache called iBatis. In 2010, this project was migrated to Google Code by Apache Software Foundation and renamed as MyBatis. MyBatis is a Java-based persistence layer framework. MyBatis eliminates almost all manual setting of JDBC code and parameters as well as retrieval of result sets. MyBatis uses simple XML or annotations for configuration and raw mapping to map interfaces and Java’s POJOs (Plain Old Java Objects) to records in the database.

2. Development environment construction

3. Maven Web project creation

4. SSM integration

The following describes the integration of the three frameworks. For setting up the environment and creating the project, see the blog post above. In this integration, I divided two configuration files, namely spring-Mybatis. XML, which contains the configuration files of Spring and Mybatis, and another one is the configuration file of spring-MVC. In addition, there are two resource files: JDBC. Propertis and log4j. Properties. The complete directory structure is as follows:


Use frameworks that are newer versions:

Spring 4.0.2 RELEASE

Spring MVC 4.0.2 RELEASE

MyBatis 3.2.6

4.1. Maven introduces the required JAR packages

In order to avoid the need to introduce JAR packages, I will directly present all the required JAR packages, which are basic JAR packages, each package is annotated for what to do, so I won’t go into more details.

pom.xml

<properties> <! --> <spring.version>4.0.2.RELEASE</spring.version> <! <mybatis. Version >3.2.6</mybatis. Version > <! -- Log4j log file management package version --> <slf4j.version>1.7.7</slf4j.version> <log4j.version>1.2.17</log4j.version> </properties> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <! <scope>test</scope> </dependency> <! <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> <! Mybatis </groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <! Mybatis </groupId> <artifactId>mybatis </artifactId> The < version > 1.2.2 < / version > < / dependency > <! <dependency> <groupId> Javax </groupId> <artifactId> Javaee - API </artifactId> <version>7.0</version> </dependency> <! <dependency> <groupId> Mysql </groupId> <artifactId>mysql-connector-java</artifactId> The < version > 5.1.30 < / version > < / dependency > <! DBCP jar package; > <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> The < version > 1.2.2 < / version > < / dependency > <! JSTL </artifactId> JSTL </artifactId> <version>1.2</version> </dependency> <! -- Log file management package --> <! -- log start --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <! -- Format the object, Alibaba </groupId> <artifactId>fastjson</artifactId> <version>1.1.41</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> <! -- log end --> <! <dependency> <groupId>org.codehaus. Jackson </groupId> <artifactId>jackson-mapper-asl</artifactId> The < version > 1.9.13 < / version > < / dependency > <! <dependency> <groupId> Commons -fileupload</groupId> <artifactId> Commons -fileupload</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId> Commons -io</groupId> <artifactId> < version > 2.4 < / version > < / dependency > < the dependency > < groupId > Commons - codec < / groupId > The < artifactId > Commons - codec < / artifactId > < version > 1.9 < / version > < / dependency > < / dependencies >Copy the code

4.2 Integration of Spring and MyBatis

After all the required JAR packages have been imported, the integration of Spring and MyBatis will be carried out first, and then JUnit will be tested.


4.2.1. Set up the JDBC property file

Jdbc.properties (file encoding changed to UTF-8)

. Driver = com. Mysql. JDBC driver url = JDBC: mysql: / / 10.221.10.111:8080 / db_zsl username = demao password = demao # define the initial number of connections InitialSize =0 # Define the maximum number of connections maxActive=20 # Define the maximum idle maxIdle=20 # define the minimum idle minIdle=1 # Define the maximum waiting time maxWait=60000Copy the code

4.2.2. Establish the spring-Mybatis. XML configuration file

This file is used to complete the integration of Spring and Mybatis. There are not many lines of configuration, mainly automatic scanning, automatic injection, configuration of the database. Notes are also very detailed, you will understand.

spring-mybatis.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:p="http://www.springframework.org/schema/p" 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-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd "> <! <context:component-scan base-package="com.cn.hnust" /> <! <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:jdbc.properties" /> </bean> <bean id="dataSource" class="org.apache.commons.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="${initialSize}"></property> <! --> <property name="maxActive" value="${maxActive}"> <property name="maxIdle" value="${maxIdle "></property> <! <property name="minIdle" value="${minIdle "></property> <! Property name="maxWait" value="${maxWait}"></property> </bean> <! -- Perfect integration of Spring and MyBatis Don't need mybatis configuration mapping file - > < bean id = "sqlSessionFactory" class = "org. Mybatis. Spring. SqlSessionFactoryBean" > < property name="dataSource" ref="dataSource" /> <! - automatic scanning mapping. The XML file - > < property name = "mapperLocations" value = "classpath: com/cn/hnust/mapping / *. XML" > < / property > </bean> <! -- DAO interface package name, Spring will automatically find below class -- > < bean class = "org. Mybatis. Spring. Mapper. MapperScannerConfigurer" > < property name = "basePackage" value="com.cn.hnust.dao" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> </bean> <! Transaction Manager, use JtaTransactionManager for global tx --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> </beans>Copy the code

4.2.3 Log4j configuration

Log4j is an open source project of Apache. By using Log4j, you can control the destination of log messages to console, files, GUI components. Even socket servers, NT event loggers, UNIX Syslog daemons, 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 Log4j configuration is simple and generic. Here is a basic configuration that doesn’t need to be changed much in other projects. Check out this blog post if you want to make adjustments or learn about the various Log4j configurations

Blog.csdn.net/zhshulin/ar…

The configuration file directory is shown below:


log4j.properties

# define the LOG output level log4j. RootLogger = INFO, the Console, the File # define LOG output destination for Console log4j. Appender. The Console = org.. Apache log4j. ConsoleAppender . Log4j appenders. Console. Target = System. # out the flexibility to specify the log output format, The following line is to specify the specific format of the log4j. Appender. Console. The layout = org.. Apache log4j. PatternLayout Log4j. Appender. Console. Layout. ConversionPattern = % [c] - % m % n # File size to specified size to create a new File log4j. Appender. The File = Org, apache log4j. RollingFileAppender # log4j. The output directory appender. File. The File = logs/SSM. Log # definition File maximum size . Log4j appenders. File. MaxFileSize = 10 MB # output so log, Said if switch to the DEBUG output above the DEBUG level logs log4j. Appender. File. The Threshold = ALL log4j. Appender. File. The layout = org.. Apache log4j. PatternLayout  log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%nCopy the code

4.2.4 JUnit Test

After the above steps (up to 4.2.2, log4j doesn’t matter), we have completed the integration of Spring and Mybatis so that we can write a piece of test code to see if it works.

4.2.4.1 Create a test table

Since we need to test, then we need to build a test table in the database, this table is built very simple, SQL statement:

DROP TABLE IF EXISTS `user_t`; CREATE TABLE `user_t` ( `id` int(11) NOT NULL AUTO_INCREMENT, `user_name` varchar(40) NOT NULL, `password` varchar(255) NOT NULL, `age` int(4) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8; /*Data for the table user_t */ insert into 'user_t' (' id ',' user_name ',' password ',' age ') values (1,' test ','sfasgfaf',24);Copy the code

4.2.4.2 Create code automatically using MyBatis Generator

Refer to the blog: blog.csdn.net/zhshulin/ar…

This automatically creates the entity class, MyBatis mapping file, and THE DAO interface from the table. Of course, I’m in the habit of changing the generated interface name to IUserDao instead of using the UserMapper it generated directly. You don’t have to change it if you don’t want the trouble. Copy the files to the project when you are done. As shown in figure:


4.2.4.3 Establish Service interface and implementation class

Directory structure:


The specific content is given below:

IUserService.java

package com.cn.hnust.service;

import com.cn.hnust.pojo.User;

public interface IUserService {
	public User getUserById(int userId);
}Copy the code

UserServiceImpl.java

package com.cn.hnust.service.impl; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.cn.hnust.dao.IUserDao; import com.cn.hnust.pojo.User; import com.cn.hnust.service.IUserService; @Service("userService") public class UserServiceImpl implements IUserService { @Resource private IUserDao userDao; @Override public User getUserById(int userId) { // TODO Auto-generated method stub return this.userDao.selectByPrimaryKey(userId); }}Copy the code

4.2.4.4 Establish the test class

The test class is created in SRC /test/ Java. The comment section of the test class below is a common test method when Spring is not used. If you are using Spring, you can use annotations to import configuration files and classes, and then inject service interface objects to test.

If the test is successful, Spring and Mybatis have been integrated successfully. The output is printed to the console using Log4j.

package org.zsl.testmybatis; import javax.annotation.Resource; import org.apache.log4j.Logger; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.alibaba.fastjson.JSON; import com.cn.hnust.pojo.User; import com.cn.hnust.service.IUserService; @ RunWith (SpringJUnit4ClassRunner. Class) / / said inherited SpringJUnit4ClassRunner class @ ContextConfiguration (locations = {"classpath:spring-mybatis.xml"}) public class TestMyBatis { private static Logger logger = Logger.getLogger(TestMyBatis.class); // private ApplicationContext ac = null; @Resource private IUserService userService = null; // @Before // public void before() { // ac = new ClassPathXmlApplicationContext("applicationContext.xml"); // userService = (IUserService) ac.getBean("userService"); // } @Test public void test1() { User user = userService.getUserById(1); // System.out.println(user.getUserName()); // logger.info(" value: "+ user.getUsername ()); logger.info(JSON.toJSONString(user)); }}Copy the code

Test results:


So far, the integration of Spring and Mybatis has been completed. Now we continue to integrate SpringMVC.

4.3. Integrate SpringMVC

The integration of the two frameworks has been completed above, the SpringMVC configuration file is placed separately, and then the integration is configured in web.xml.

4.3.1. Configure spring-mVC.xml

Configuration inside the comments are also very detailed, here will not say, mainly automatic scan controller, view mode, annotation start these three.

<? 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:p="http://www.springframework.org/schema/p" 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-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd "> <! <context:component-scan base-package="com.cn.hnust. Controller "/> <! -- Avoid AJAX execution in IE Returns a JSON download file -- > < bean id = "mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html; charset=UTF-8</value> </list> </property> </bean> <! -- Enable annotations for SpringMVC 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> <! - define the jump of the file before the suffix, view mode configuration - > < bean class = "org. Springframework. Web. Servlet. The InternalResourceViewResolver" > <! The action method return string is automatically prefixed and postfixed. Become an available URL address --> <property name="prefix" value="/ web-INF/JSP /" /> <property name="suffix" value=".jsp" /> </bean> <! -- Configuration file upload, if you do not use file upload can not configure, of course, if not, <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <! Property name="defaultEncoding" value=" UTF-8 "/> <! <property name="maxUploadSize" value="10485760000" /> <! <property name="maxInMemorySize" value="40960" /> </bean> </beans>Copy the code

4.3.2. Configure the web. XML file

The Servlet for spring-Mybatis. XML and spring-MVC configuration is designed to complete SSM integration. The previous 2 framework integration does not require any configuration here. Configuration also has detailed comments, not much explanation.

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>Archetype Created Web Application</display-name> <! <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mybatis.xml</param-value> </context-param> <! -- encodingFilter --> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <async-supported>true</async-supported> <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> <! - Spring listener - > < listener > < listener - class > org. Springframework. Web. Context. ContextLoaderListener < / listener - class > </listener> <! -- Prevent Spring memory overflow listener --> <listener> <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener> <! -- Spring MVC servlet --> <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:spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> <async-supported>true</async-supported> </servlet> <servlet-mapping> <servlet-name>SpringMVC</servlet-name> <! *. Do, *. Struts --> <url-pattern>/</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>/index.jsp</welcome-file> </welcome-file-list> </web-app>Copy the code

4.3.3, test,

So far the SSM three framework integration has been completed, next test, if successful, congratulations, if failed, continue debugging, as a programmer is constantly fighting with bugs!

4.3.3.1. Create a JSP page


Showuser.jsp This page simply outputs the user name to complete a simple process.

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> < HTML > <title> </title> </head> <body> ${user.userName} </body> </html>Copy the code

4.3.3.2. Establish the UserController class

UserController. Java controller

package com.cn.hnust.controller; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import com.cn.hnust.pojo.User; import com.cn.hnust.service.IUserService; @Controller @RequestMapping("/user") public class UserController { @Resource private IUserService userService; @RequestMapping("/showUser") public String toIndex(HttpServletRequest request,Model model){ int userId = Integer.parseInt(request.getParameter("id")); User user = this.userService.getUserById(userId); model.addAttribute("user", user); return "showUser"; }}Copy the code

4.3.3.3 deployment project

Enter the address: localhost:8080/ project name /user/showUser? id=1

At this point, the integration of the three SSM frameworks is complete, on which you can add additional functionality.