Three Framework Integration

Source: Internet
Author: User

37956105
37956105
Using SSM (Spring, SPRINGMVC, and MyBatis) has been around for three months, the project has no technical difficulties, based on the existing technology can achieve the desired function, of course, there are certainly a lot of areas to improve. The process of SSM integration was not documented before, and it was just a good time to build a new project based on one of its own, and better than the project. The previous problem solving process and methods are not recorded in time, later in their own small project encountered me to organize and share. This time, let's talk about the three framework integration process. Personally, the use of frames is not difficult, the key to understand their ideas, which is very helpful for us to improve the level of programming. However, if you do not use, talk about the idea becomes an armchair!!! First technology, then thought. Practice is the real truth. (The blog address can be viewed via image watermark)

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

If necessary, see the previous blog post: http://blog.csdn.net/zhshulin/article/details/30779873

3. Maven Web project Creation

If necessary, see the previous blog post: http://blog.csdn.net/zhshulin/article/details/37921705

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.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.driverurl=jdbc:mysql://10.221.10.111:8080/db_zslusername=demaopassword=demao# Define initial connections initialsize=0# define maximum number of connections maxactive=20# define maximum idle maxidle=20# define minimum idle minidle=1# define maximum wait time maxwait=600004.2.2, Establishing a 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

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, even a socket server, NT Event recorder, UNIX Syslog Daemon, etc. 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:
http://blog.csdn.net/zhshulin/article/details/37937365
The configuration file directory is given below:

Log4j.properties

Define log output level log4j.rootlogger=info,console,file# Define the logging output destination to console log4j.appender.console= The org.apache.log4j.consoleappenderlog4j.appender.console.target=system.out# provides the flexibility to specify the log output format, The following line specifies the specific format log4j.appender.Console.layout = Org.apache.log4j.patternlayoutlog4j.appender.console.layout.conversionpattern=[%c]-%m%n # When the file size reaches the specified size, a new file is generated log4j.appender.File = org.apache.log4j.rollingfileappender# Specifies the output directory log4j.appender.File.File = logs/ssm.log# definition file Maximum size log4j.appender.File.MaxFileSize = 10mb# output so log, If switching to debug indicates output debug above level log Log4j.appender.File.Threshold = ALLlog4j.appender.File.layout = Org.apache.log4j.PatternLayoutlog4j.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 ( id int (one) not NULL auto_increment, user_name varchar (+) NOT NULL, password varchar (255) is 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, using MyBatis Generator to create code automatically

Reference post: http://blog.csdn.net/zhshulin/article/details/23912615

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 (U Serid); } }
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.SpringJUnit4ClassRunner; Import Com.alibaba.fastjson.json;import Com.cn.hnust.pojo.user;import com.cn.hnust.service.IUserService; @RunWith (Springjunit4classrunner.class)//indicates that the Springjunit4classrunner class @contextconfiguration (locations = {") is inherited 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 (US Er.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.

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

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"%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" > ${user.username}
4.3.3.2, establishing 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; @[email protected] ("/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"; }}
4.3.3.3, Deployment Projects

Input Address: localhost:8080/Project name/user/showuser?id=1

At this point, the SSM three framework of integration is completed, on this basis can add additional functions.

This article from Shu_lin's CSDN blog, full-text address please click: 37956105?utm_source=copy

Three Framework Integration

Related Article

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.