SSM Framework spring+springmvc+mybatis--Detailed Integration tutorial

Source: Internet
Author: User
Tags aop log4j

1. Basic Concepts

1.1. Spring

Spring is an open source framework, and spring is a lightweight Java development framework that emerged in 2003 by Rod Johnson in his book expert one-on-one development and Some of the concepts and prototypes elaborated in design are derived. It is created to address the complexities of enterprise application development. Spring uses basic JavaBean to accomplish things that were previously only possible by EJBS. However, the use of spring is not limited to server-side development. From the standpoint of simplicity, testability, and loose coupling, any Java application can benefit from spring. In short, spring is a lightweight control inversion (IoC) and aspect-oriented (AOP) container framework.

1.2, SPRINGMVC

Spring MVC is a follow-on product of springframework and has been integrated into spring Web flow. Spring MVC separates the roles of controllers, model objects, dispatchers, and handler objects, and this separation makes them easier to customize.

1.3, MyBatis

MyBatis is an open source project for Apache Ibatis, which was migrated to Google code by the Apache Software Foundation in 2010 and renamed MyBatis. MyBatis is a Java-based persistence layer framework. The persistence layer framework provided by Ibatis includes SQL maps and Data Access Objects (DAO) MyBatis eliminates the manual setting of almost all JDBC code and parameters and the retrieval of result sets. MyBatis uses simple XML or annotations for configuration and raw mapping, mapping interfaces and Java POJOs (Plain old Java Objects, ordinary Java objects) to records in a database.

2. Construction of development environment

Technology selection (only part of the technology is listed)

1, back-end

Service Framework: Dubbo, Zookeeper, rest services

Cache: Redis, Ehcache

Message middleware: ActiveMQ

Load balancing: Nginx

Distributed files: Fastdfs

Database connection pool: Alibaba Druid 1.0

Core Framework: Spring framework

Security framework: Apache Shiro 1.2

View Frame: Spring MVC 4.0

Server-side validation: Hibernatevalidator 5.1

Layout frame: Sitemesh 2.4

Workflow Engine: Activiti 5.15

Task Scheduler: Quartz 1.8.5

Persistence Layer Framework: MyBatis 3.2

Log management: slf4j 1.7, log4j

Tool classes: Apache Commons, Jackson 2.2, Xstream 1.4, dozer 5.3, POI

2. Front-end

JS frame: jQuery1.9.

CSS Framework: Bootstrap 4 Metronic

Client authentication: Jqueryvalidation Plugin.

Rich Text: Ckecitor

File Management: Ckfinder

Dynamic tab: Jerichotab

Data table: Jqgrid

dialog box: JQuery jbox

Tree structure controls: JQuery Ztree

Other components: Bootstrap 4 metronic

3. Support

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

Database support: Currently only support MySQL database, but not limited to the database, the next version of the upgrade multi-data source switching and database read and write separation: Oracle, SQL Server, H2, etc.

Support development environment: Eclipse, MyEclipse, Ras, idea, etc.

Classic Introduction:

SOURCE structure

Welcome to study the relevant technology to learn about the framework of technology or the source of friends directly add to seek (Penguin): 2042849237

More detailed source code reference: Http://xxx/technology

3. Maven Web project Creation

4. SSM Integration

The following is mainly about the integration of the three frameworks, as for the construction of the environment and the creation of projects, see the above blog post. I've divided 2 profiles for this integration, The Spring-mybatis.xml, which contains the spring and MyBatis profiles, and a configuration file for Spring-mvc, plus 2 resource files: Jdbc.propertis and log4j.properties. The complete directory structure is as follows (finally, the source code, not recommended to use the source directly, because this tutorial already has all the codes):

The use of frames is a newer version:

Spring 4.0.2 RELEASE

Spring MVC 4.0.2 RELEASE

MyBatis 3.2.6

4.1. Maven introduces the required jar package

In order to make it easier to say later without the need to introduce the jar package, I am here to give all the necessary jar package, this is the basic jar package, each package is what the comment, no longer say.

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

All of the required jar packages are introduced, first with the integration of spring and MyBatis, then the JUnit test, first look at a project map:

4.2.1, creating a JDBC Property file

Jdbc.properties (File code modified to Utf-8)

Driver=com.mysql.jdbc.driver

Url=jdbc:mysql://10.221.10.111:8080/db_zsl

Username=demao

Password=demao

#定义初始连接数

Initialsize=0

#定义最大连接数

Maxactive=20

#定义最大空闲

Maxidle=20

#定义最小空闲

Minidle=1

#定义最长等待时间

maxwait=60000

4.2.2, establishing spring-mybatis.xml configuration file

This file is used to complete the integration of spring and MyBatis. There are not many lines in the configuration, the main is automatic scanning, automatic injection, configuration database. The notes are also very detailed, and we'll see.

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

Configuration of 4.2.3 and log4j

In order to facilitate debugging, the general will use the log to output information, log4j is an Apache open source project, through the use of log4j, we can control the log information delivery destination is the console, files, GUI components, or even a socket server, NT Event recorder, Unixsyslog Daemon; We can also control the output format of each log, and by defining the level of each log information, we can control the log generation process more carefully.

LOG4J configuration is very simple, but also common, the following gives a basic configuration, for other projects do not need to do much adjustment, if you want to make adjustments or want to understand the various configurations of log4j, see I reproduced a blog post, very detailed:

The configuration file directory is given below:

Log4j.properties

#定义LOG输出级别

Log4j.rootlogger=info,console,file

#定义日志输出目的地为控制台

Log4j.appender.console=org.apache.log4j.consoleappender

Log4j.appender.console.target=system.out

#可以灵活地指定日志输出格式, the following line specifies the specific format

Log4j.appender.Console.layout = Org.apache.log4j.PatternLayout

LOG4J.APPENDER.CONSOLE.LAYOUT.CONVERSIONPATTERN=[%C]-%m%n

#文件大小到达指定尺寸的时候产生一个新的文件

Log4j.appender.File = Org.apache.log4j.RollingFileAppender

#指定输出目录

Log4j.appender.File.File = Logs/ssm.log

#定义文件最大大小

Log4j.appender.File.MaxFileSize = 10MB

Output so log, if switching to debug indicates output debug above level log

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 (not to 4.2.2,log4j), we have completed the integration of spring and mybatis so that we can write a test code to try and succeed.

4.2.4.1, creating test tables

Now that we need to test, we need to build a test table in the database, which is very simple and the SQL statement is:

DROP TABLE IF EXISTS user_t ;

CREATE TABLE user_t (

idInt (one) not NULL auto_increment,

user_namevarchar (+) is not NULL,

passwordvarchar (255) Not NULL,

ageInt (4) is 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, using MyBatis Generator to create code automatically

This automatically creates the entity class, the MyBatis mapping file, and the DAO interface based on the table, and, of course, I'm used to changing the generated interface name to Iuserdao instead of the usermapper generated directly from it. If you don't want trouble, you can do it without change. When you are finished, copy the files to the project.

4.2.4.3, establishing service interfaces and implementing classes

Directory structure:

Here's what you'll get:

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, build test class

The test class is established in Src/test/java, and the commented out part of the test class below is a general test method when you do not use spring, and if you use spring then you can use annotations to introduce the configuration file and class, and then inject the service interface object can be tested.

If the test is successful, it means that spring and mybatis have been integrated successfully. The output information 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.springjunit4cla***unner;

Import Com.alibaba.fastjson.JSON;

Import Com.cn.hnust.pojo.User;

Import Com.cn.hnust.service.IUserService;

@RunWith (Springjunit4cla***unner.class)//means inheriting the Springjunit4cla***unner 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:

At this point, the integration of the two frameworks of spring and MyBatis is completed, and the SPRINGMVC integration is continued below.

4.3, integrated Springmvc

The above has completed the consolidation of the 2 frameworks, the SPRINGMVC configuration file is placed separately, and then the integration is configured in Web. Xml.

4.3.1, configuration Spring-mvc.xml

Configuration inside the note is also very detailed, this is not said, mainly automatic scanning controller, view mode, annotated start of 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, configuring the Web. xml file

This is the case with the introduction of Spring-mybatis.xml and the configuration of the Spring-mvc servlet in order to complete SSM integration, the previous 2 framework consolidation does not need to be configured here. The configuration has the same detailed comment, not much explanation.

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

So far has completed the SSM three framework of integration, next Test, if successful, then congratulations, if you fail, continue to debug it, as a programmer is constantly fighting against bugs!

4.3.3.1, new JSP page

showuser.jsp This page only 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, establishing 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";

}

}

SSM Framework spring+springmvc+mybatis--Detailed Integration tutorial

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.