一、springmvc+mybaits的系統架構:

第一步:整合dao層
mybatis和spring整合,通過spring管理mapper接口。
使用mapper的掃描器自動掃描mapper接口在spring中進行注冊。
第二步:整合service層
通過spring管理 service接口。
使用配置方式將service接口配置在spring配置文件中。
實現事務控制。
第三步:整合springmvc
由於springmvc是spring的模塊,不需要整合。
整合步驟:
一、首先創建Mybatis自己的配置文件(例如:sqlMapConfig.xml)
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!-- 全局setting配置,根據需要添加 --> <!-- 配置別名 --> <typeAliases> <!-- 批量掃描別名 --> <package name="cn.itcast.ssm.po"/> </typeAliases> <!-- 配置mapper 由於使用spring和mybatis的整合包進行mapper掃描,這里不需要配置了。 必須遵循:mapper.xml和mapper.java文件同名且在一個目錄 --> <!-- <mappers> </mappers> --> </configuration>
tips:使用自動掃描器時,mapper.xml文件如果和mapper.java接口在一個目錄則此處不用定義mappers.
二、創建applicationContext-dao.xml文件,用以配置數據源、事務管理,配置SqlSessionFactory、mapper掃描器。
1 <beans xmlns="http://www.springframework.org/schema/beans" 2 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" 3 xmlns:context="http://www.springframework.org/schema/context" 4 xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 5 xsi:schemaLocation="http://www.springframework.org/schema/beans 6 http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 7 http://www.springframework.org/schema/mvc 8 http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 9 http://www.springframework.org/schema/context 10 http://www.springframework.org/schema/context/spring-context-3.2.xsd 11 http://www.springframework.org/schema/aop 12 http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 13 http://www.springframework.org/schema/tx 14 http://www.springframework.org/schema/tx/spring-tx-3.2.xsd "> 15 16 <!-- 加載db.properties文件中的內容,db.properties文件中key命名要有一定的特殊規則 --> 17 <context:property-placeholder location="classpath:db.properties" /> 18 <!-- 配置數據源 ,dbcp --> 19 20 <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" 21 destroy-method="close"> 22 <property name="driverClassName" value="${jdbc.driver}" /> 23 <property name="url" value="${jdbc.url}" /> 24 <property name="username" value="${jdbc.username}" /> 25 <property name="password" value="${jdbc.password}" /> 26 <property name="maxActive" value="30" /> 27 <property name="maxIdle" value="5" /> 28 </bean> 29 <!-- sqlSessionFactory --> 30 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> 31 <!-- 數據庫連接池 --> 32 <property name="dataSource" ref="dataSource" /> 33 <!-- 加載mybatis的全局配置文件 --> 34 <property name="configLocation" value="classpath:mybatis/sqlMapConfig.xml" /> 35 </bean> 36 <!-- mapper掃描器 --> 37 <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> 38 <!-- 掃描包路徑,如果需要掃描多個包,中間使用半角逗號隔開 --> 39 <property name="basePackage" value="cn.itcast.ssm.mapper"></property> 40 <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> 41 </bean> 42 43 </beans>
db.properties:
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/mybatis jdbc.username=root jdbc.password=mysql
tips:使用逆向工程生成po類及mapper(單表增刪改查)

三、手動定義商品查詢mapper及商品查詢dao接口
ItemsMapperCustom.xml
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > 3 <mapper namespace="cn.itcast.ssm.mapper.ItemsMapperCustom" > 4 5 <!-- 定義商品查詢的sql片段,就是商品查詢條件 --> 6 <sql id="query_items_where"> 7 <!-- 使用動態sql,通過if判斷,滿足條件進行sql拼接 --> 8 <!-- 商品查詢條件通過ItemsQueryVo包裝對象 中itemsCustom屬性傳遞 --> 9 <if test="itemsCustom!=null"> 10 <if test="itemsCustom.name!=null and itemsCustom.name!=''"> 11 items.name LIKE '%${itemsCustom.name}%' 12 </if> 13 </if> 14 15 </sql> 16 17 <!-- 商品列表查詢 --> 18 <!-- parameterType傳入包裝對象(包裝了查詢條件) 19 resultType建議使用擴展對象 20 --> 21 <select id="findItemsList" parameterType="cn.itcast.ssm.po.ItemsQueryVo" 22 resultType="cn.itcast.ssm.po.ItemsCustom"> 23 SELECT items.* FROM items 24 <where> 25 <include refid="query_items_where"></include> 26 </where> 27 </select> 28 29 </mapper
ItemsMapperCustom.java
1 package cn.itcast.ssm.mapper; 2 3 import cn.itcast.ssm.po.Items; 4 import cn.itcast.ssm.po.ItemsCustom; 5 import cn.itcast.ssm.po.ItemsExample; 6 import cn.itcast.ssm.po.ItemsQueryVo; 7 8 import java.util.List; 9 import org.apache.ibatis.annotations.Param; 10 11 public interface ItemsMapperCustom { 12 //商品查詢列表 13 public List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo)throws Exception; 14 }
四、整合service,讓spring管理service接口,進行事務管理配置。
首先,定義Service接口和Service的實現類
1 package cn.itcast.ssm.service; 2 3 import java.util.List; 4 5 import cn.itcast.ssm.po.ItemsCustom; 6 import cn.itcast.ssm.po.ItemsQueryVo; 7 8 /** 9 * 10 * <p>Title: ItemsService</p> 11 * <p>Description:商品管理service </p> 12 * <p>Company: www.itcast.com</p> 13 * @author 傳智.燕青 14 * @date 2015-4-13下午3:48:09 15 * @version 1.0 16 */ 17 public interface ItemsService { 18 19 //商品查詢列表 20 public List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo) throws Exception; 21 22 //根據id查詢商品信息 23 /** 24 * 25 * <p>Title: findItemsById</p> 26 * <p>Description: </p> 27 * @param id 查詢商品的id 28 * @return 29 * @throws Exception 30 */ 31 public ItemsCustom findItemsById(Integer id) throws Exception; 32 33 //修改商品信息 34 /** 35 * 36 * <p>Title: updateItems</p> 37 * <p>Description: </p> 38 * @param id 修改商品的id 39 * @param itemsCustom 修改的商品信息 40 * @throws Exception 41 */ 42 public void updateItems(Integer id,ItemsCustom itemsCustom) throws Exception; 43 44 45 }
1 package cn.itcast.ssm.service.impl; 2 3 import java.util.List; 4 5 import org.springframework.beans.BeanUtils; 6 import org.springframework.beans.factory.annotation.Autowired; 7 8 import cn.itcast.ssm.mapper.ItemsMapper; 9 import cn.itcast.ssm.mapper.ItemsMapperCustom; 10 import cn.itcast.ssm.po.Items; 11 import cn.itcast.ssm.po.ItemsCustom; 12 import cn.itcast.ssm.po.ItemsQueryVo; 13 import cn.itcast.ssm.service.ItemsService; 14 15 /** 16 * 17 * <p>Title: ItemsServiceImpl</p> 18 * <p>Description: 商品管理</p> 19 * <p>Company: www.itcast.com</p> 20 * @author 傳智.燕青 21 * @date 2015-4-13下午3:49:54 22 * @version 1.0 23 */ 24 public class ItemsServiceImpl implements ItemsService{ 25 26 @Autowired 27 private ItemsMapperCustom itemsMapperCustom; 28 29 @Autowired 30 private ItemsMapper itemsMapper; 31 32 @Override 33 public List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo) 34 throws Exception { 35 //通過ItemsMapperCustom查詢數據庫 36 return itemsMapperCustom.findItemsList(itemsQueryVo); 37 } 38 39 @Override 40 public ItemsCustom findItemsById(Integer id) throws Exception { 41 42 Items items = itemsMapper.selectByPrimaryKey(id); 43 //中間對商品信息進行業務處理 44 //.... 45 //返回ItemsCustom 46 ItemsCustom itemsCustom = new ItemsCustom(); 47 //將items的屬性值拷貝到itemsCustom 48 BeanUtils.copyProperties(items, itemsCustom); 49 50 return itemsCustom; 51 52 } 53 54 @Override 55 public void updateItems(Integer id, ItemsCustom itemsCustom) throws Exception { 56 //添加業務校驗,通常在service接口對關鍵參數進行校驗 57 //校驗 id是否為空,如果為空拋出異常 58 59 //更新商品信息使用updateByPrimaryKeyWithBLOBs根據id更新items表中所有字段,包括 大文本類型字段 60 //updateByPrimaryKeyWithBLOBs要求必須轉入id 61 itemsCustom.setId(id); 62 itemsMapper.updateByPrimaryKeyWithBLOBs(itemsCustom); 63 } 64 65 }
然后,在spring容器配置service(applicationContext-service.xml)
1 <bean id="itemsService" class="cn.itcast.ssm.service.impl.ItemsServiceImpl"/> 2 </beans>
配置事務控制,applicationContext-transcation.xml
1 <beans xmlns="http://www.springframework.org/schema/beans" 2 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" 3 xmlns:context="http://www.springframework.org/schema/context" 4 xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 5 xsi:schemaLocation="http://www.springframework.org/schema/beans 6 http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 7 http://www.springframework.org/schema/mvc 8 http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 9 http://www.springframework.org/schema/context 10 http://www.springframework.org/schema/context/spring-context-3.2.xsd 11 http://www.springframework.org/schema/aop 12 http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 13 http://www.springframework.org/schema/tx 14 http://www.springframework.org/schema/tx/spring-tx-3.2.xsd "> 15 16 <!-- 事務管理器 17 對mybatis操作數據庫事務控制,spring使用jdbc的事務控制類 18 --> 19 <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> 20 <!-- 數據源 21 dataSource在applicationContext-dao.xml中配置了 22 --> 23 <property name="dataSource" ref="dataSource"/> 24 </bean> 25 26 <!-- 通知 --> 27 <tx:advice id="txAdvice" transaction-manager="transactionManager"> 28 <tx:attributes> 29 <!-- 傳播行為 --> 30 <tx:method name="save*" propagation="REQUIRED"/> 31 <tx:method name="delete*" propagation="REQUIRED"/> 32 <tx:method name="insert*" propagation="REQUIRED"/> 33 <tx:method name="update*" propagation="REQUIRED"/> 34 <tx:method name="find*" propagation="SUPPORTS" read-only="true"/> 35 <tx:method name="get*" propagation="SUPPORTS" read-only="true"/> 36 <tx:method name="select*" propagation="SUPPORTS" read-only="true"/> 37 </tx:attributes> 38 </tx:advice> 39 <!-- aop --> 40 <aop:config> 41 <aop:advisor advice-ref="txAdvice" pointcut="execution(* cn.itcast.ssm.service.impl.*.*(..))"/> 42 </aop:config> 43 44 </beans>
五、配置springmvc.xml文件
1 <beans xmlns="http://www.springframework.org/schema/beans" 2 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" 3 xmlns:context="http://www.springframework.org/schema/context" 4 xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 5 xsi:schemaLocation="http://www.springframework.org/schema/beans 6 http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 7 http://www.springframework.org/schema/mvc 8 http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 9 http://www.springframework.org/schema/context 10 http://www.springframework.org/schema/context/spring-context-3.2.xsd 11 http://www.springframework.org/schema/aop 12 http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 13 http://www.springframework.org/schema/tx 14 http://www.springframework.org/schema/tx/spring-tx-3.2.xsd "> 15 16 <!-- 可以掃描controller、service、... 17 這里讓掃描controller,指定controller的包 18 --> 19 <context:component-scan base-package="cn.itcast.ssm.controller"></context:component-scan> 20 21 22 <!--注解映射器 --> 23 <!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/> --> 24 <!--注解適配器 --> 25 <!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/> --> 26 27 <!-- 使用 mvc:annotation-driven代替上邊注解映射器和注解適配器配置 28 mvc:annotation-driven默認加載很多的參數綁定方法, 29 比如json轉換解析器就默認加載了,如果使用mvc:annotation-driven不用配置上邊的RequestMappingHandlerMapping和RequestMappingHandlerAdapter 30 實際開發時使用mvc:annotation-driven 31 --> 32 <mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven> 33 34 35 <!-- 視圖解析器 36 解析jsp解析,默認使用jstl標簽,classpath下的得有jstl的包 37 --> 38 <bean 39 class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 40 <!-- 配置jsp路徑的前綴 --> 41 <property name="prefix" value="/WEB-INF/jsp/"/> 42 <!-- 配置jsp路徑的后綴 --> 43 <property name="suffix" value=".jsp"/> 44 </bean> 45 46 <!-- 自定義參數綁定 --> 47 <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> 48 <!-- 轉換器 --> 49 <property name="converters"> 50 <list> 51 <!-- 日期類型轉換 --> 52 <bean class="cn.itcast.ssm.controller.converter.CustomDateConverter"/> 53 </list> 54 </property> 55 56 57 </bean> 58 </beans>
六、編寫controller
1 @RequestMapping("/items") 2 public class ItemsController { 3 4 @Autowired 5 private ItemsService itemsService; 6 7 // 商品查詢 8 @RequestMapping("/queryItems") 9 public ModelAndView queryItems(HttpServletRequest request) throws Exception { 10 //測試forward后request是否可以共享 11 12 System.out.println(request.getParameter("id")); 13 14 // 調用service查找 數據庫,查詢商品列表 15 List<ItemsCustom> itemsList = itemsService.findItemsList(null); 16 17 // 返回ModelAndView 18 ModelAndView modelAndView = new ModelAndView(); 19 // 相當 於request的setAttribut,在jsp頁面中通過itemsList取數據 20 modelAndView.addObject("itemsList", itemsList); 21 22 // 指定視圖 23 // 下邊的路徑,如果在視圖解析器中配置jsp路徑的前綴和jsp路徑的后綴,修改為 24 // modelAndView.setViewName("/WEB-INF/jsp/items/itemsList.jsp"); 25 // 上邊的路徑配置可以不在程序中指定jsp路徑的前綴和jsp路徑的后綴 26 modelAndView.setViewName("items/itemsList"); 27 28 return modelAndView; 29 30 } 31 }
七、編寫JSP頁面(省略...)
八、加載spring容器
在web.xml文件中進行如下配置
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3 xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 4 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 5 id="WebApp_ID" version="2.5"> 6 <display-name>springmvc_mybatis1208</display-name> 7 8 <!-- 加載spring容器 --> 9 <context-param> 10 <param-name>contextConfigLocation</param-name> 11 <param-value>/WEB-INF/classes/spring/applicationContext-*.xml</param-value> 12 </context-param> 13 <listener> 14 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 15 </listener> 16 17 18 <!-- springmvc前端控制器 --> 19 <servlet> 20 <servlet-name>springmvc</servlet-name> 21 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 22 <!-- contextConfigLocation配置springmvc加載的配置文件(配置處理器映射器、適配器等等) 如果不配置contextConfigLocation,默認加載的是/WEB-INF/servlet名稱-serlvet.xml(springmvc-servlet.xml) --> 23 <init-param> 24 <param-name>contextConfigLocation</param-name> 25 <param-value>classpath:spring/springmvc.xml</param-value> 26 </init-param> 27 </servlet> 28 29 <servlet-mapping> 30 <servlet-name>springmvc</servlet-name> 31 <!-- 第一種:*.action,訪問以.action結尾 由DispatcherServlet進行解析 第二種:/,所以訪問的地址都由DispatcherServlet進行解析,對於靜態文件的解析需要配置不讓DispatcherServlet進行解析 32 使用此種方式可以實現 RESTful風格的url 第三種:/*,這樣配置不對,使用這種配置,最終要轉發到一個jsp頁面時, 仍然會由DispatcherServlet解析jsp地址,不能根據jsp頁面找到handler,會報錯。 --> 33 <url-pattern>*.action</url-pattern> 34 </servlet-mapping> 35 36 <!-- post亂碼過慮器 --> 37 <filter> 38 <filter-name>CharacterEncodingFilter</filter-name> 39 <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> 40 <init-param> 41 <param-name>encoding</param-name> 42 <param-value>utf-8</param-value> 43 </init-param> 44 </filter> 45 <filter-mapping> 46 <filter-name>CharacterEncodingFilter</filter-name> 47 <url-pattern>/*</url-pattern> 48 </filter-mapping> 49 50 <welcome-file-list> 51 <welcome-file>index.html</welcome-file> 52 <welcome-file>index.htm</welcome-file> 53 <welcome-file>index.jsp</welcome-file> 54 <welcome-file>default.html</welcome-file> 55 <welcome-file>default.htm</welcome-file> 56 <welcome-file>default.jsp</welcome-file> 57 </welcome-file-list> 58 </web-app>
