Reprint: http://blog.csdn.net/zhshulin
Using SSM( spring Spring MVC, Spring MVC and Mymatis have been more than three months. There are no technical difficulties in the project. Based on the existing technology, we can achieve the desired functions. Of course, there must be many areas for improvement. The integration process of SSM was not recorded before. This time, it was rebuilt based on a small project of its own, and it was better than the project. In the past, the process and methods of solving problems were not recorded in time. I will reorganize and share them when I meet in my own small projects. This time, let's talk about the integration process of the three frameworks. Personally, I think it is not difficult to use the framework. The key is to understand its ideas, which is very helpful for us to improve our programming level. Nevertheless, if you can't use it, talking about ideas becomes talking about soldiers on paper!!! First technology, then thought. True knowledge comes from practice. (Blog addresses can be viewed through image watermarking)
1. Basic concepts
1.1,Spring
Spring is an open source framework, and Spring was a lightweight one that emerged in 2003 Java The development framework is derived from some concepts and prototypes elaborated by Rod Johnson in his book Expert One-On-One J2EE Development and Design. It is created to solve the complexity of enterprise application development. Spring uses basic JavaBean s to accomplish things previously only possible with EJB s. However, Spring's use is not limited to server-side development. From simplicity to feasibility test From a sexual and loosely coupled perspective, 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-up product of Spring FrameWork and has been integrated into Spring Web Flow. Spring MVC is separated Controller Model object The separation of roles of dispatchers and handler objects makes them easier to customize.
1.3,MyBatis
MyBatis apache An open source project iBatis In 2010, the project was moved from apache software foundation to google code and renamed MyBatis. MyBatis is a Java-based Persistence Layer Framework. iBATIS Persistence Layer The framework includes SQL Maps and Data Access Objects (DAO) MyBatis, which eliminates manual settings of almost all JDBC codes and parameters and retrieval of result sets. MyBatis uses simple XML or annotations to configure and map interfaces and Java POJOs (Plain Old Java Objects, plain Java objects) to original mappings data base Records in.
2. Construction of Development Environment
If necessary, refer to the previous blog: http://blog.csdn.net/zhshulin/article/details/30779873
3. Maven Web Project Creation
If necessary, refer to the previous blog: http://blog.csdn.net/zhshulin/article/details/37921705
4. SSM Integration
The integration of the three frameworks is introduced below. For the construction of the environment and the creation of the project, see the above blog. This integration I divided into two configuration files, spring-mybatis.xml, including spring and mybatis configuration files, and a spring-mvc configuration file, in addition to two resource files: jdbc. properties and log4j.properties. The full directory structure is as follows (the source code download address is attached at the end, and it is not recommended to use the source code directly because the tutorial already has all the code):
The frameworks used 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
For the convenience of not introducing JAR packages when I say later, I will give all the JAR packages needed directly. These are basic JAR packages. Every package has comments on what it does, so I won't say much more.
pom.xml
4.2. Integration of Spring and MyBatis
After all the required JAR packages are introduced, the integration of Spring and MyBatis is carried out first, and then the JUnit test is carried out. First, a project structure diagram is shown.
4.2.1. Establishing JDBC Property File
jdbc.properties (file code 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 number of initial connections
-
initialSize=0
-
#Define the maximum number of connections
-
maxActive=20
-
#Define maximum idleness
-
maxIdle=20
-
#Define minimum idleness
-
minIdle=1
-
#Define the longest waiting time.
-
maxWait=60000
4.2.2. Establish spring-mybatis.xml configuration file
This file is used to integrate spring and mybatis. There are not many lines of configuration, the main thing is automatic scanning, automatic injection, configuration database. The annotations are also very detailed, you can see by looking at them.
spring-mybatis.xml
-
<?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>
-
-
<property name="maxIdle" value="${maxIdle}"></property>
-
-
<property name="minIdle" value="${minIdle}"></property>
-
-
<property name="maxWait" value="${maxWait}"></property>
-
</bean>
-
-
-
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
-
<property name="dataSource" ref="dataSource" />
-
-
<property name="mapperLocations" value="classpath:com/cn/hnust/mapping/*.xml"></property>
-
</bean>
-
-
-
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
-
<property name="basePackage" value="com.cn.hnust.dao" />
-
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
-
</bean>
-
-
-
<bean id="transactionManager"
-
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
-
<property name="dataSource" ref="dataSource" />
-
</bean>
-
-
</beans>
Configuration of 4.2.3 and Log4j
In order to facilitate debugging, log is usually used to output information. Log4j is Apache An open source project that we can control by using Log4j Journal The destination of information transmission is Console Documents, GUI Components, even socket servers, NT Event logger, UNIX SyslogDaemon process We can also control the output format of each log; by defining the level of each log information, we can control the generation process of the log more carefully.
Log4j's configuration is very simple and general. Here's a basic configuration. It doesn't need much adjustment to change to other projects. If you want to adjust or understand the various configurations of Log4j, refer to a blog post I reprinted. It's very detailed:
http://blog.csdn.net/zhshulin/article/details/37937365
The following is the configuration file directory:
log4j.properties
-
#Define LOG output level
-
log4j.rootLogger=INFO,Console,File
-
#Define the log output destination as the console
-
log4j.appender.Console=org.apache.log4j.ConsoleAppender
-
log4j.appender.Console.Target=System.out
-
#You can specify the log output format flexibly. The next line specifies the specific format.
-
log4j.appender.Console.layout = org.apache.log4j.PatternLayout
-
log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n
-
-
#A new file is generated when the file size reaches the specified size.
-
log4j.appender.File = org.apache.log4j.RollingFileAppender
-
#Designated output directory
-
log4j.appender.File.File = logs/ssm.log
-
#Define the maximum file size
-
log4j.appender.File.MaxFileSize = 10MB
-
#Output logs, if replaced by DEBUG, indicate output logs above DEBUG level.
-
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 (4.2.2, log4j doesn't match or affect), we have completed the integration of Spring and mybatis, so that we can write a test code to see if it's successful.
4.2.4.1. Create test tables
Since we need to test, then we need to build a test table in the database. This table is very simple. The SQL statement is as follows:
-
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. Automatically create code using MyBatis Generator
Reference blog: http://blog.csdn.net/zhshulin/article/details/23912615
This automatically creates entity classes, MyBatis mapping files, and DAO interfaces based on tables. Of course, I'm used to changing the name of the generated interface to IUserDao instead of directly using it to generate UserMapper. If you don't want to be in trouble, you can do nothing about it. Copy the file to the project after completion. As shown in the figure:
4.2.4.3. Establishing Service Interface and Implementation Class
Directory structure:
Specific contents are 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) {
-
-
return this.userDao.selectByPrimaryKey(userId);
-
}
-
-
}
4.2.4.4. Establishing test classes
The test class is built in src/test/java. The annotated part of the test class below is a test method in general when Spring is not used. If Spring is used, the configuration file and class can be introduced by annotation, and then the service interface object can be injected into the test.
If the test is successful, Spring and Mymatis have been integrated successfully. The output information is printed to the console by 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)
-
@ContextConfiguration(locations = {"classpath:spring-mybatis.xml"})
-
-
public class TestMyBatis {
-
private static Logger logger = Logger.getLogger(TestMyBatis.class);
-
-
@Resource
-
private IUserService userService = null;
-
-
-
-
-
-
-
-
@Test
-
public void test1() {
-
User user = userService.getUserById(1);
-
-
-
logger.info(JSON.toJSONString(user));
-
}
-
}
Test results:
So far, the integration of Spring and mybatis is completed, and the integration of Spring MVC is continuing below.
4.3. Integrating Spring MVC
The above two frameworks have been integrated. Spring MVC's configuration files are placed separately and then integrated in web.xml.
4.3.1, configure spring-mvc.xml
The annotations in the configuration are also very detailed, let's not say here, mainly the automatic scanning controller, view mode, annotation start three.
-
<?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" />
-
-
<bean id="mappingJacksonHttpMessageConverter"
-
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
-
<property name="supportedMediaTypes">
-
<list>
-
<value>text/html;charset=UTF-8</value>
-
</list>
-
</property>
-
</bean>
-
-
<bean
-
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
-
<property name="messageConverters">
-
<list>
-
<ref bean="mappingJacksonHttpMessageConverter" />
-
</list>
-
</property>
-
</bean>
-
-
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
-
-
<property name="prefix" value="/WEB-INF/jsp/" />
-
<property name="suffix" value=".jsp" />
-
</bean>
-
-
-
<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>
4.3.2. Configure the web.xml file
The introduction of spring-mybatis.xml and the configuration of spring-mvc Servlet s are for SSM integration. The previous two framework integration does not require any configuration here. Configuration is also annotated in detail, with little explanation.
web.xml
-
<?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>
-
-
<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>
-
-
<listener>
-
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
-
</listener>
-
-
<listener>
-
<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
-
</listener>
-
-
-
<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>
-
-
<url-pattern>/</url-pattern>
-
</servlet-mapping>
-
<welcome-file-list>
-
<welcome-file>/index.jsp</welcome-file>
-
</welcome-file-list>
-
-
</web-app>
4.3.3. Testing
At this point, the integration of the three main frameworks of SSM has been completed. Next, test it. If it succeeds, congratulate you. If it fails, continue debugging. As a programmer, you are fighting against BUG all the time.
4.3.3.1. New jsp page
showUser.jsp This page only outputs the user name to complete a complete simple process.
-
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
-
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
-
<html>
-
<head>
-
<title>test</title>
-
</head>
-
-
<body>
-
${user.userName}
-
</body>
-
</html>
4.3.3.2. Establish 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";
-
}
-
}
4.3.3.3. Deployment projects
Enter address: localhost:8080 / project name / user/showUser?id=1
So far, the integration of the three frameworks of SSM has been completed, and other functions can be added on this basis.