原文:https://blog.csdn.net/bieleyang/article/details/77862042css
做用:html
SSM框架是spring MVC ,spring和mybatis框架的整合,是標準的MVC模式,將整個系統劃分爲表現層,controller層,service層,DAO層四層java
使用spring MVC負責請求的轉發和視圖管理mysql
spring實現業務對象管理,mybatis做爲數據對象的持久化引擎web
原理:面試
SpringMVC:spring
1.客戶端發送請求到DispacherServlet(分發器)sql
2.由DispacherServlet控制器查詢HanderMapping,找處處理請求的Controller數據庫
3.Controller調用業務邏輯處理後,返回ModelAndViewapache
4.DispacherSerclet查詢視圖解析器,找到ModelAndView指定的視圖
5.視圖負責將結果顯示到客戶端
Spring:咱們平時開發接觸最多的估計就是IOC容器,它能夠裝載bean(也就是咱們Java中的類,固然也包括service dao裏面的),有了這個機制,咱們就不用在每次使用這個類的時候爲它初始化,不多看到關鍵字new。另外spring的aop,事務管理等等都是咱們常常用到的。
Mybatis:mybatis是對jdbc的封裝,它讓數據庫底層操做變的透明。mybatis的操做都是圍繞一個sqlSessionFactory實例展開的。mybatis經過配置文件關聯到各實體類的Mapper文件,Mapper文件中配置了每一個類對數據庫所需進行的sql語句映射。在每次與數據庫交互時,經過sqlSessionFactory拿到一個sqlSession,再執行sql命令。
使用方法:
要完成一個功能:
DataBase ===> Entity ===> Mapper.xml ===> Mapper.Java ===> Service.java ===> Controller.java ===> Jsp.
====================================================================================================================================
Spring MVC 擁有控制器,做用跟Struts相似,接收外部請求,解析參數傳給服務層
Spring 容器屬於協調上下文,管理對象間的依賴,提供事務機制
mybatis 屬於orm持久層框架,將業務實體 與數據表聯合 起來
Spring MVC 控制層,想當與 Struts的做用
Spring 控制反轉和依賴注入 建立對象交由容器管理,達到了解耦的做用
mybatis 主要用來操做數據庫(數據庫的增刪改查)
IOC:控制反轉,是一種下降對象之間耦合關係的設計思想,面試的時候最好能說出來個例子,加深理解。例子:租房子,之前租房子須要一個房子一個房子找,費時費力,而後如今加入一個房屋中介,把你須要的房型告訴中介,就能夠直接選到須要的房子,中介就至關於spring容器。
AOP:面向切面編程,是面向對象開發的一種補充,它容許開發人員在不改變原來模型的基礎上動態的修改模型以知足新的需求,如:動態的增長日誌、安全或異常處理等。AOP使業務邏輯各部分間的耦合度下降,提升程序可重用性,提升開發效率。
Controller,View層由於耦合度比較高,於是要結合在一塊兒開發,可是也能夠看做一個總體獨立於前兩個層進行開發。這樣,在層與層以前咱們只須要知道接口的定義,調用接口便可完成所須要的邏輯單元應用,一切顯得很是清晰簡單。
Service邏輯層設計
====================================================================================================================================
最近在學習Spring+SpringMVC+MyBatis的整合。如下是參考網上的資料本身實踐操做的詳細步驟。
Spring是一個開源框架,Spring是於2003 年興起的一個輕量級的Java 開發框架,由Rod Johnson 在其著做Expert One-On-One J2EE Development and Design中闡述的部分理念和原型衍生而來。它是爲了解決企業應用開發的複雜性而建立的。Spring使用基本的JavaBean來完成之前只可能由EJB完成的事情。然而,Spring的用途不只限於服務器端的開發。從簡單性、可測試性和鬆耦合的角度而言,任何Java應用均可以從Spring中受益。 簡單來講,Spring是一個輕量級的控制反轉(IoC)和麪向切面(AOP)的容器框架。
Spring MVC屬於SpringFrameWork的後續產品,已經融合在Spring Web Flow裏面。Spring MVC 分離了控制器、模型對象、分派器以及處理程序對象的角色,這種分離讓它們更容易進行定製。
MyBatis 本是apache的一個開源項目iBatis, 2010年這個項目由apache software foundation 遷移到了google code,而且更名爲MyBatis 。MyBatis是一個基於Java的持久層框架。iBATIS提供的持久層框架包括SQL Maps和Data Access Objects(DAO)MyBatis 消除了幾乎全部的JDBC代碼和參數的手工設置以及結果集的檢索。MyBatis 使用簡單的 XML或註解用於配置和原始映射,將接口和 Java 的POJOs(Plain Old Java Objects,普通的 Java對象)映射成數據庫中的記錄。
參看以前的博文:http://www.cnblogs.com/zyw-205520/p/4767633.html
下面主要介紹三大框架的整合,至於環境的搭建以及項目的建立,參看上面的博文。此次整合我分了2個配置文件,分別是spring-mybatis.xml,包含spring和mybatis的配置文件,還有個是spring-mvc的配置文件,此外有2個資源文件:jdbc.propertis和log4j.properties。完整目錄結構以下(最後附上源碼下載地址):
使用框架的版本:
Spring 4.0.2 RELEASE
Spring MVC 4.0.2 RELEASE
MyBatis 3.2.6
在pom.xml中引入jar包
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.javen.maven01</groupId> <artifactId>maven01</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>maven01 Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <!-- spring版本號 --> <spring.version>4.0.2.RELEASE</spring.version> <!-- mybatis版本號 --> <mybatis.version>3.2.6</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>3.8.1</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.2.2</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>5.1.36</version> </dependency> <!-- 導入dbcp的jar包,用來在applicationContext.xml中配置數據庫 --> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.2.2</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.1.41</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>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.9</version> </dependency> </dependencies> <build> <finalName>maven01</finalName> <plugins> <plugin> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-maven-plugin</artifactId> <version>9.2.8.v20150217</version> <configuration> <httpConnector> <port>80</port> </httpConnector> <stopKey>shutdown</stopKey> <stopPort>9966</stopPort> </configuration> </plugin> </plugins> </build> </project>
配置裏面的註釋也很詳細,主要是自動掃描控制器,視圖模式,註解的啓動這三個。
<?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"> <!-- 自動掃描該包,使SpringMVC認爲包下用了@controller註解的類是控制器 --> <context:component-scan base-package="com.javen.controller" /> <!-- 擴充了註解驅動,能夠將請求參數綁定到控制器參數 --> <mvc:annotation-driven/> <!-- 靜態資源處理 css js imgs --> <mvc:resources location="/resources/**" mapping="/resources"/> <!--避免IE執行AJAX時,返回JSON出現下載文件 --> <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> <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 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" /> <!-- 啓用是爲了推遲文件解析,以便捕獲文件大小異常 --> <property name="resolveLazily" value="true"/> </bean> <!-- 配置ViewResolver 。可用多個ViewResolver 。使用order屬性排序。 InternalResourceViewResolver 放在最後--> <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver"> <property name="order" value="1"></property> <property name="mediaTypes"> <map> <!-- 告訴視圖解析器,返回的類型爲json格式 --> <entry key="json" value="application/json" /> <entry key="xml" value="application/xml" /> <entry key="htm" value="text/htm" /> </map> </property> <property name="defaultViews"> <list> <!-- ModelAndView裏的數據變成JSON --> <bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" /> </list> </property> <property name="ignoreAcceptHeader" value="true"></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> </beans>
配置的spring-mvc的Servlet就是爲了完成SpringMVC+MAVEN的整合。
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>
爲了方便調試,通常都會使用日誌來輸出信息,Log4j是Apache的一個開放源代碼項目,經過使用Log4j,咱們能夠控制日誌信息輸送的目的地是控制檯、文件、GUI組件,甚至是套接口服務器、NT的事件記錄器、UNIX Syslog守護進程等;咱們也能夠控制每一條日誌的輸出格式;經過定義每一條日誌信息的級別,咱們可以更加細緻地控制日誌的生成過程。
Log4j的配置很簡單,並且也是通用的,下面給出一個基本的配置,換到其餘項目中也無需作多大的調整,若是想作調整或者想了解Log4j的各類配置,參看我轉載的一篇博文,很詳細:http://blog.csdn.net/zhshulin/article/details/37937365
下面給出配置文件目錄:
log4j.properties
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
package com.javen.model; public class User { private Integer id; private String userName; private String password; private Integer age; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName == null ? null : userName.trim(); } public String getPassword() { return password; } public void setPassword(String password) { this.password = password == null ? null : password.trim(); } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return "User [id=" + id + ", userName=" + userName + ", password=" + password + ", age=" + age + "]"; } }
package com.javen.controller; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.javen.model.User; @Controller @RequestMapping("/user") // /user/** public class UserController { private static Logger log=LoggerFactory.getLogger(UserController.class); // /user/test?id=1 @RequestMapping(value="/test",method=RequestMethod.GET) public String test(HttpServletRequest request,Model model){ int userId = Integer.parseInt(request.getParameter("id")); System.out.println("userId:"+userId); User user=null; if (userId==1) { user = new User(); user.setAge(11); user.setId(1); user.setPassword("123"); user.setUserName("javen"); } log.debug(user.toString()); model.addAttribute("user", user); return "index"; } }
在瀏覽器中輸入:http://localhost/user/test?id=1
到此 SpringMVC+Maven 整合完畢
取消3.2.2 web.xml中註釋的代碼
jdbc.properties(文件編碼修改成utf-8)
driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/maven username=root password=root #定義初始鏈接數 initialSize=0 #定義最大鏈接數 maxActive=20 #定義最大空閒 maxIdle=20 #定義最小空閒 minIdle=1 #定義最長等待時間 maxWait=60000
此時的目錄結構爲
這個文件就是用來完成spring和mybatis的整合的。這裏面也沒多少行配置,主要的就是自動掃描,自動注入,配置數據庫。註釋也很詳細,你們看看就明白了。
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.javen" /> <!-- 引入配置文件 --> <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> <!-- spring和MyBatis完美整合,不須要mybatis的配置映射文件 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 自動掃描mapping.xml文件 --> <property name="mapperLocations" value="classpath:com/javen/mapping/*.xml"></property> </bean> <!-- DAO接口所在包名,Spring會自動查找其下的類 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.javen.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>
通過以上步驟,咱們已經完成了Spring和mybatis的整合,這樣咱們就能夠編寫一段測試代碼來試試是否成功了。
既然咱們須要測試,那麼咱們就須要創建在數據庫中創建一個測試表,這個表建的很簡單,SQL語句爲:
-- ---------------------------- -- Table structure for `user_t` -- ---------------------------- 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=3 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of user_t -- ---------------------------- INSERT INTO `user_t` VALUES ('1', '測試', '345', '24'); INSERT INTO `user_t` VALUES ('2', 'javen', '123', '10');
參考博文:http://blog.csdn.net/zhshulin/article/details/23912615
這個可根據表自動建立實體類、MyBatis映射文件以及DAO接口,固然,我習慣將生成的接口名改成IUserDao,而不是直接用它生成的UserMapper。若是不想麻煩就能夠不改。完成後將文件複製到工程中。如圖:
下面給出具體的內容:
IUserService.jave
package com.javen.service; import com.javen.model.User; public interface IUserService { public User getUserById(int userId); }
UserServiceImpl.java
package com.javen.service.impl; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.javen.dao.IUserDao; import com.javen.model.User; import com.javen.service.IUserService; @Service("userService") public class UserServiceImpl implements IUserService { @Resource private IUserDao userDao; public User getUserById(int userId) { // TODO Auto-generated method stub return this.userDao.selectByPrimaryKey(userId); } }
測試類在src/test/java中創建,下面測試類中註釋掉的部分是不使用Spring時,通常狀況下的一種測試方法;若是使用了Spring那麼就可使用註解的方式來引入配置文件和類,而後再將service接口對象注入,就能夠進行測試了。
若是測試成功,表示Spring和Mybatis已經整合成功了。輸出信息使用的是Log4j打印到控制檯。
package com.javen.testmybatis; import javax.annotation.Resource; import org.apache.log4j.Logger; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.alibaba.fastjson.JSON; import com.javen.model.User; import com.javen.service.IUserService; @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 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("值:"+user.getUserName()); logger.info(JSON.toJSONString(user)); } }
測試結果
UserController.java 控制器
package com.javen.controller; import java.io.File; import java.io.IOException; import java.util.Map; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import org.apache.commons.io.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import com.javen.model.User; import com.javen.service.IUserService; @Controller @RequestMapping("/user") // /user/** public class UserController { private static Logger log=LoggerFactory.getLogger(UserController.class); @Resource private IUserService userService; // /user/test?id=1 @RequestMapping(value="/test",method=RequestMethod.GET) public String test(HttpServletRequest request,Model model){ int userId = Integer.parseInt(request.getParameter("id")); System.out.println("userId:"+userId); User user=null; if (userId==1) { user = new User(); user.setAge(11); user.setId(1); user.setPassword("123"); user.setUserName("javen"); } log.debug(user.toString()); model.addAttribute("user", user); return "index"; } // /user/showUser?id=1 @RequestMapping(value="/showUser",method=RequestMethod.GET) public String toIndex(HttpServletRequest request,Model model){ int userId = Integer.parseInt(request.getParameter("id")); System.out.println("userId:"+userId); User user = this.userService.getUserById(userId); log.debug(user.toString()); model.addAttribute("user", user); return "showUser"; } // /user/showUser2?id=1 @RequestMapping(value="/showUser2",method=RequestMethod.GET) public String toIndex2(@RequestParam("id") String id,Model model){ int userId = Integer.parseInt(id); System.out.println("userId:"+userId); User user = this.userService.getUserById(userId); log.debug(user.toString()); model.addAttribute("user", user); return "showUser"; } // /user/showUser3/{id} @RequestMapping(value="/showUser3/{id}",method=RequestMethod.GET) public String toIndex3(@PathVariable("id")String id,Map<String, Object> model){ int userId = Integer.parseInt(id); System.out.println("userId:"+userId); User user = this.userService.getUserById(userId); log.debug(user.toString()); model.put("user", user); return "showUser"; } // /user/{id} @RequestMapping(value="/{id}",method=RequestMethod.GET) public @ResponseBody User getUserInJson(@PathVariable String id,Map<String, Object> model){ int userId = Integer.parseInt(id); System.out.println("userId:"+userId); User user = this.userService.getUserById(userId); log.info(user.toString()); return user; } // /user/{id} @RequestMapping(value="/jsontype/{id}",method=RequestMethod.GET) public ResponseEntity<User> getUserInJson2(@PathVariable String id,Map<String, Object> model){ int userId = Integer.parseInt(id); System.out.println("userId:"+userId); User user = this.userService.getUserById(userId); log.info(user.toString()); return new ResponseEntity<User>(user,HttpStatus.OK); } //文件上傳、 @RequestMapping(value="/upload") public String showUploadPage(){ return "user_admin/file"; } @RequestMapping(value="/doUpload",method=RequestMethod.POST) public String doUploadFile(@RequestParam("file")MultipartFile file) throws IOException{ if (!file.isEmpty()) { log.info("Process file:{}",file.getOriginalFilename()); } FileUtils.copyInputStreamToFile(file.getInputStream(), new File("E:\\",System.currentTimeMillis()+file.getOriginalFilename())); return "succes"; } }
file.jsp
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Insert title here</title> </head> <body> <h1>上傳文件</h1> <form method="post" action="/user/doUpload" enctype="multipart/form-data"> <input type="file" name="file"/> <input type="submit" value="上傳文件"/> </form> </body> </html>
index.jsp
<html> <body> <h2>Hello World!</h2> </body> </html>
showUser.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>測試</title> </head> <body> ${user.userName} </body> </html>
至此,完成Spring+SpingMVC+mybatis這三大框架整合完成。
輸入地址:http://localhost/user/jsontype/2