. html
參考博文:Eclipse4.6(Neon) + Tomcat8 + MAVEN3.3.9 + SVN項目完整環境搭建java
2.1. python
2.2. mysql
2.3. web
2.4. spring
2.5. 完成後目錄結構圖sql
2.5 (可選)設置: 選中項目 單擊右鍵設置;數據庫
項目編碼換成UTF-8:Properties -> Resource -> Text file encodingexpress
設置默認的JRE:Properties -> Java Build Path -> 選項卡 Librariesapache
設置 Properties -> Project Facets
選中3.0 可能會出錯
解決方法: 修改該項目路徑下的 .settings/ org.eclipse.wst.common.project.facet.core.xml 文件;
<!-- 修改成須要的版本號 -->
<?xml version="1.0" encoding="UTF-8"?>
<faceted-project>
<fixed facet="wst.jsdt.web"/>
<installed facet="java" version="1.8"/>
<installed facet="jst.web" version="3.0"/>
<installed facet="wst.jsdt.web" version="1.0"/>
</faceted-project>
重啓Eclipse可能會警告!按照提示操做便可。
或者參考網站: Cannot change version of project facet Dynamic web
2個配置文件:spring-mybatis.xml、spring-mvc.xml
2個資源文件:jdbc.propertis、log4j.properties
完整目錄結構以下圖:
本教程使用部分jar包的版本:
Spring: 4.3.3.RELEASE
Spring MVC: 4.3.2.RELEASE
MyBatis: 3.4.1
mybatis-spring: 1.3.0
mysql-connector-java: 6.0.4
javax.servlet-api:3.1.0
commons-dbcp: 1.4
fastjson: 1.2.17
commons-io: 2.5
commons-codec: 1.10
推薦2個maven找jar包配置的網站:
代碼清單 3-1:pom.xml
<properties>
<!-- spring版本號 -->
<spring.version>4.3.3.RELEASE</spring.version>
<!-- mybatis版本號 -->
<mybatis.version>3.4.1</mybatis.version>
<!-- log4j日誌文件管理包版本 -->
<slf4j.version>1.7.7</slf4j.version>
<log4j.version>1.2.17</log4j.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<!-- 表示開發的時候引入,發佈的時候不會加載此包 -->
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<!-- spring核心包 -->
<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核心包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<!-- mybatis/spring包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
<!-- 導入java ee jar 包 -->
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
</dependency>
<!-- 導入Mysql數據庫連接jar包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.4</version>
</dependency>
<!-- 導入dbcp的jar包,用來在applicationContext.xml中配置數據庫 -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<!-- JSTL標籤類 -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- 日誌文件管理包 -->
<!-- log start -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<!-- 格式化對象,方便輸出日誌 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.17</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 -->
<!-- 映入JSON -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.8.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.8.3</version>
</dependency>
<!-- 上傳組件包 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.10</version>
</dependency>
</dependencies>
全部須要的JAR包都引入之後,首先進行Spring與MyBatis的整合,而後再進行JUnit測試,先看一個項目結構圖:
代碼清單 3-2:jdbc.properties
jdbc.driver_class=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql:///test?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false
jdbc.username=username
jdbc.password=password
#定義初始鏈接數
initialSize=0
#定義最大鏈接數
maxActive=20
#定義最大空閒
maxIdle=20
#定義最小空閒
minIdle=1
#定義最長等待時間
maxWait=60000
這個文件就是用來完成spring和mybatis的整合的。這裏面也沒多少行配置,主要的就是自動掃描,自動注入,配置數據庫。註釋也很詳細,你們看看就明白了。
代碼清單 3-3: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:mybatis-spring="http://mybatis.org/schema/mybatis-spring" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.3.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<!-- 支持註解 -->
<context:annotation-config></context:annotation-config>
<!--自動掃描 :經過註解過濾被掃描的類 -->
<context:component-scan base-package="org.sei" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Repository"/>
<context:include-filter type="annotation" expression="org.springframework.stereotype.Service"/>
</context:component-scan>
<!-- 引入配置文件 -->
<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="${jdbc.driver_class}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.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>
<!-- spring和MyBatis完美整合,不須要mybatis的配置映射文件 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- 自動掃描mapping.xml文件 -->
<property name="mapperLocations" value="classpath*:org/sei/mapping/*.xml"></property>
</bean>
<!-- DAO接口所在包名,Spring會自動查找其下的類 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="org.sei.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>
詳情參考博文:【轉】Log4j配置詳解;我這裏直接貼碼。
代碼清單 3-4:log4j.properties
#定義LOG輸出級別
log4j.rootLogger=INFO,Console,File
#定義日誌輸出目的地爲控制檯
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.Target=System.out
#能夠靈活地指定日誌輸出格式,下面一行是指定具體的格式
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
# 輸出因此日誌,若是換成DEBUG表示輸出DEBUG以上級別日誌
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
通過以上步驟(到3.2.2,log4j不配也沒影響),咱們已經完成了Spring和mybatis的整合,這樣咱們就能夠編寫一段測試代碼來試試是否成功了。
用SQL語句在test數據庫中創建一個測試表user_t。
代碼清單 3-5:test_t.sql
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,'test1','pwd1',21);
INSERT INTO `user_t`(`id`,`user_name`,`password`,`age`) VALUES (2,'test2','pwd2',22);
INSERT INTO `user_t`(`id`,`user_name`,`password`,`age`) VALUES (3,'測試3','pwd2',23);
參考博文:使用MyBatis Generator自動建立代碼
這個可根據表自動建立實體類、MyBatis映射文件以及DAO接口;固然我習慣將生成的接口名改成 UserDao,而不是直接用它生成的UserMapper。若是不想麻煩能夠不改。完成後將文件複製到工程中。如圖:
注意:
自動生成的Dao和Pojo就只改包名,主要別忘記修改UserMapper.xml文件;
目錄結構:
代碼清單 3-6:UserService.jave
package org.sei.service;
import org.sei.pojo.User;
public interface UserService {
public User getUserById(int userId);
}
代碼清單 3-7:UserServiceImpl.jave
package org.sei.service.impl;
import javax.annotation.Resource;
import org.sei.dao.UserDao;
import org.sei.pojo.User;
import org.sei.service.UserService;
//import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service //注意:此註解不寫會報錯
public class UserServiceImpl implements UserService {
//@Autowired 和 @Resource
//這裏二者均可以用;具體詳情請參考下面2個網站:
//http://www.cnblogs.com/leiOOlei/p/3713779.html
//http://www.zhihu.com/question/39356740
@Resource
private UserDao userDao;
@Override
public User getUserById(int userId) {
return this.userDao.selectByPrimaryKey(userId);
}
}
測試類在src/test/java中創建,下面測試類中_註釋掉的部分是不使用Spring時,通常狀況下的一種測試方法_;若是使用了Spring那麼就可使用註解的方式來引入配置文件和類,而後再將service接口對象注入,就能夠進行測試了。
若是測試成功,表示Spring和Mybatis已經整合成功了。輸出信息使用的是Log4j打印到控制檯。
代碼清單 3-8:TestMyBatis.jave
package org.sei.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 org.sei.pojo.User;
import org.sei.service.UserService;
@RunWith(SpringJUnit4ClassRunner.class) //表示繼承了SpringJUnit4ClassRunner類
@ContextConfiguration(locations = {"classpath:spring-mybatis.xml"})
public class TestMyBatis {
private static Logger logger = Logger.getLogger(TestMyBatis.class);
// private ApplicationContext ac = null;
@Resource
private UserService userService = null;
// @Before
// public void before() {
// ac = new ClassPathXmlApplicationContext("applicationContext.xml");
// userService = (IUserService) ac.getBean("userService");
// }
@Test
public void test1() {
User user = userService.getUserById(2);
// System.out.println(user.getUserName());
// logger.info("值:"+user.getUserName());
logger.info(JSON.toJSONString(user));
}
}
注意: 我用的是MySQL Connector/J 6.x 新版驅動,直接報異常!!!
若有須要請看博文:MySQL Connector/J 6.x jdbc.properties 配置, mysql-connector-java-6.0.4.jar 異常
結果如圖:
至此,完成Spring和mybatis這兩大框架的整合,下面在繼續進行SpringMVC的整合。
上面已經完成了2大框架的整合,SpringMVC的配置文件單獨放,而後在web.xml中配置整合。
配置裏面的註釋也很詳細,在此就不說了;主要是自動掃描控制器,視圖模式,註解的啓動這三個。
**注意:**配置文件中的一行:class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"
個人項目裏是jackson2.X版本的,若是你用的是jackson1.X版本的,不用寫"2"。
代碼清單 3-9:spring-mvc.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:mybatis-spring="http://mybatis.org/schema/mybatis-spring" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.3.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<!-- 支持註解 -->
<context:annotation-config></context:annotation-config>
<!-- 自動掃描該包,使SpringMVC認爲包下用了@controller註解的類是控制器 (經過註解過濾被掃描的類)-->
<context:component-scan base-package="org.sei" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Repository"/>
<context:include-filter type="annotation" expression="org.springframework.stereotype.Service"/>
</context:component-scan>
<!--避免IE執行AJAX時,返回JSON出現下載文件;注意:MappingJackson2 -->
<bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>
<!-- 啓動SpringMVC的註解功能,完成請求和註解POJO的映射 -->
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="mappingJacksonHttpMessageConverter" /> <!-- JSON轉換器 -->
</list>
</property>
</bean>
<!-- 定義跳轉的文件的先後綴 ,視圖模式配置-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 這裏的配置個人理解是自動給後面action的方法return的字符串加上前綴和後綴,變成一個 可用的url地址 -->
<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>
這裏面對spring-mybatis.xml的引入以及配置的spring-mvc的Servlet就是爲了完成SSM整合,以前2框架整合不須要在此處進行任何配置。配置同樣有詳細註釋,很少解釋了。
代碼清單 3-10: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>
<!-- Spring和mybatis的配置文件 -->
<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>
<!-- Spring監聽器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 防止Spring內存溢出監聽器 -->
<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>
接下來測試一下,極可能失敗,不要緊,繼續調試;遇到問題是應該的,解決問題才能進步!
(我也在不停的和BUG做鬥爭啊...)
詳情參考博文:springmvc controller junit 測試
包的導入
註解的使用
MySQL Connector/J 6.x 的新變化
複製到代碼的時候要根據本機環境修改相應的代碼
參考: