Abstract: Spring is an open source framework. Spring is a lightweight Java development framework developed 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 short, Spring is A lightweight inversion of control (IoC) and faceted (A

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: hibernateValidator 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: Query1.9.

CSS framework: Bootstrap 4 Metronic

Client-side validation: jqueryValidation 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

Classic introduction:

Source structure




Welcome everyone to study the relevant technology together willing to understand the framework technology or source code friends directly add beg (penguin) : 2042849237

More detailed source code reference source: minglisoft.cn/technology

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

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

4.0.2. RELEASE

3.2.6

1.7.7

1.2.17

junit

junit

4.11

test

org.springframework

spring-core

${spring.version}

org.springframework

spring-web

${spring.version}

org.springframework

spring-oxm

${spring.version}

org.springframework

spring-tx

${spring.version}

org.springframework

spring-jdbc

${spring.version}

org.springframework

spring-webmvc

${spring.version}

org.springframework

spring-aop

${spring.version}

org.springframework

spring-context-support

${spring.version}

org.springframework

spring-test

${spring.version}

org.mybatis

mybatis

${mybatis.version}

org.mybatis

mybatis-spring

1.2.2

javax

javaee-api

7.0

mysql

mysql-connector-java

5.1.30

commons-dbcp

commons-dbcp

1.2.2

jstl

jstl

1.2

log4j

log4j

${log4j.version}

com.alibaba

fastjson

1.1.41

org.slf4j

slf4j-api

${slf4j.version}

org.slf4j

slf4j-log4j12

${slf4j.version}

org.codehaus.jackson

jackson-mapper-asl

1.9.13

commons-fileupload

commons-fileupload

1.3.1

commons-io

commons-io

2.4

commons-codec

commons-codec

1.9

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 connection number

initialSize=0

Define the maximum number of connections

maxActive=20

# define maximum free time

maxIdle=20

# define minimum idle

minIdle=1

# define the maximum wait time

maxWait=60000

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

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 “>

class=”org.springframework.beans.factory.config.PropertyPlaceholderConfigurer”>

destroy-method=”close”

class=”org.springframework.jdbc.datasource.DataSourceTransactionManager”>

4.2.3 Log4j configuration

Log4j is an open source project of Apache. By using Log4j, we can control the destination of log messages to the console, files, GUI components, even the socket server, NT event logger, UNIXSyslog 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 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:




log4j.properties

Define the LOG output level

log4j.rootLogger=INFO,Console,File

Define log output destination as console

log4j.appender.Console=org.apache.log4j.ConsoleAppender

log4j.appender.Console.Target=System.out

You can specify the log output format flexibly. The following line specifies the specific format

log4j.appender.Console.layout = org.apache.log4j.PatternLayout

log4j.appender.Console.layout.ConversionPattern=[%c] – %m%n

Create a new file when the file size reaches the specified size

log4j.appender.File = org.apache.log4j.RollingFileAppender

Specify the output directory

log4j.appender.File.File = logs/ssm.log

# define the maximum file size

log4j.appender.File.MaxFileSize = 10MB

Output all logs. If the value is DEBUG, the output level of logs is DEBUG or higher

log4j.appender.File.Threshold = ALL

log4j.appender.File.layout = org.apache.log4j.PatternLayout

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).

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);

}

}

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));

}

}

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.

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 “>

class=”org.springframework.http.converter.json.MappingJacksonHttpMessageConverter”>

text/html; charset=UTF-8

class=”org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter”>

class=”org.springframework.web.multipart.commons.CommonsMultipartResolver”>

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

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” >

Archetype Created Web Application

contextConfigLocation

classpath:spring-mybatis.xml

encodingFilter

org.springframework.web.filter.CharacterEncodingFilter

true

encoding

UTF-8

encodingFilter

/ *

org.springframework.web.context.ContextLoaderListener

org.springframework.web.util.IntrospectorCleanupListener

SpringMVC

org.springframework.web.servlet.DispatcherServlet

contextConfigLocation

classpath:spring-mvc.xml

1

true

SpringMVC

/

/index.jsp

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″%>

test

${user.userName}

4.3.3.2. Establish the UserController class

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”;

}

}

Welcome everyone to study the relevant technology together willing to understand the framework technology or source code friends directly add beg (penguin) : 2042849237

More detailed source code reference source: minglisoft.cn/technology