1. Basic concepts

1.1, 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.

 

1.2, for 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.

 

1.3, 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

Technology selection (only part of the technology is listed)

1, the back end

Service framework: Dubbo, ZooKeeper, and Rest

Cache: Redis, Ehcache

Message middleware: ActiveMQ

Load balancer: Nginx

Distributed file: FastDFS

Database connection pool: Alibaba Druid 1.0

Core framework: Spring Framework

Security framework: Apache Shiro 1.2

View Framework: Spring MVC 4.0

Server-side validation: Hibernate Validator 5.1

Layout framework: SiteMesh 2.4

Workflow engine: Activiti 5.15

Task scheduling: Quartz 1.8.5

Persistence layer framework: MyBatis 3.2

Log management: SLF4J 1.7, Log4j

Tools: Apache Commons, Jackson 2.2, Xstream 1.4, Dozer 5.3, POI

2, the front end,

JS framework: JQuery 1.9

CSS framework: Bootstrap 4 Metronic

Client-side Validation: JQuery Validation Plugin.

Rich text: CKEcitor

File management: CKFinder

Dynamic TAB: Jerichotab

Data table: jqGrid

Dialog box: jQuery jBox

Tree structure control: jQuery zTree

Other components: Bootstrap 4 Metronic

3, support,

Server middleware: Tomcat 6, 7, Jboss 7, WebLogic 10, WebSphere 8

Database support: Currently, the mysql database is supported, but not limited to the database. In the next version, multiple data source switchover and database read/write separation, such as Oracle, SqlServer, and H2, are supported

Support development environment: Eclipse, MyEclipse, Ras, Idea, etc

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 have 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 (with the source code download address attached at the end, it is not recommended to use the source code directly, because this tutorial already has all the code) :



Use frameworks that are newer versions:

       Spring 4.0.2 RELEASE

       Spring MVC 4.0.2 RELEASE

       MyBatis 3.2.6

3. Maven Web project creation

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. If you want to make adjustments or learn more about the various Log4j configurations, see my post for details:

The configuration file directory is shown below:



  1. Define the LOG output level
  2. log4j.rootLogger=INFO,Console,File  
  3. Define log output destination as console
  4. log4j.appender.Console=org.apache.log4j.ConsoleAppender  
  5. log4j.appender.Console.Target=System.out  
  6. You can specify the log output format flexibly. The following line specifies the specific format
  7. log4j.appender.Console.layout = org.apache.log4j.PatternLayout  
  8. log4j.appender.Console.layout.ConversionPattern=[%c] – %m%n  
  9.   
  10. Create a new file when the file size reaches the specified size
  11. log4j.appender.File = org.apache.log4j.RollingFileAppender  
  12. Specify the output directory
  13. log4j.appender.File.File = logs/ssm.log  
  14. # define the maximum file size
  15. log4j.appender.File.MaxFileSize = 10MB  
  16. Output all logs. If the value is DEBUG, the output level of logs is DEBUG or higher
  17. log4j.appender.File.Threshold = ALL  
  18. log4j.appender.File.layout = org.apache.log4j.PatternLayout  
  19. log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n 

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

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.jave package com.cn.hnust.service; import com.cn.hnust.pojo.User; public interface IUserService { public User getUserById(int userId); } 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

Welcome to study related technology together

Willing to understand the framework technology or source code of friends directly beg to exchange technology: 1903832579