SpringMVC和Mybatis (一)整合思路、整合dao、service、springmvc、加載spring

開發分層開發:前端層,業務層,持久層


sping將各層進行整合:
通過spring管理持久層的mapper
通過spring管理service,可以調用mapper接口,進行事務控制。
通過spring管理Handler,可以調用service接口
mapper、service、Handler都是javaBean


第一步整合dao層
使用mapper的掃描器自動掃描mapper接口在spring中進行註冊


第二步整合service層
使用配置方式將service接口配置在spring配置文件中。
實現事務控制,根據業務層在哪裏,事務層在哪裏。


第三步整合springmvc
不需要整合


1.加載jar包:數據庫驅動包、mybatis包、mybatis和spring整合包、log4j包、dbcp數據庫連接池包、


spring所有包、jstl包
2.創建config創建log4j.properties

config創建db.properties

3.創建包:controller、mapper、po、service、創建ItemsService.java、service.impl。

4.整合dao(mybatis和spring進行整合)
config創建mybatis包創建sqlMapConfig.xml


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同名且在一個目錄
-->
 
<!-- <mapperts></mappers> -->


</configuration>


在config創建spring創建applicationContext-dao.xml、applicationContext-service.xml、applicationContext-transaction.xml、springmvc.xml

applicationContext-dao.xml

配置:數據源、SqlSessionFactory


<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.2.xsd 
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">


  <!-- 加載配置文件 -->
  <context:property-placeholder location="classpath:db.properties" />


<!-- 數據源,使用dbcp -->
        <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName" value="${jdbc.driver}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <property name="maxActive" value="10" />
        <property name="maxIdle" value="5" />
        </bean>
        
<!-- sqlSessionFactory -->
<!-- 從mybatis-spring內查看class -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 加載mybatis配置文件 -->
<property name="configLocation" value="classpath:mybatis/sqlMapConfig.xml" />
<!-- 數據源 -->
<property name="dataSource" ref="dataSource" />
</bean>

<!-- mapper批量掃描,從mapper包中掃描出mapper接口,自動創建代理對象並且在spring容器中註冊 
將mapper接口類名和mapper.xml映射文件名稱保存一致,且在一個目錄下
自動掃描出來的mapper的bean的id爲mapper類名(首字母小寫)
-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 指定掃描包的名字
如果掃描多個包,每個包中間使用半角逗號分隔 -->
<property name="basePackage" value="cn.itcast.ssm.mapper" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>

</beans>


編寫mapper使用逆向工程
生成:
ssm.mapper和ssm.po的包


針對綜合查詢mapper,手動定義商品查詢mapper
ItemsMapperCustom.xml
sql語句:SELECT * FROM items WHERE NAME LIKE '%批量%'

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="cn.itcast.ssm.mapper.ItemsMapperCustom" >


<!-- 定義商品查詢的sql片段,就是商品查詢條件 -->
<sql id="query_items_where">
<!-- 使用動態sql,通過if判斷,滿足條件進行sql拼接 -->
<!-- 商品的查詢條件通過ItemsQueryVo的包裝屬性傳遞 -->
<if test="itemsCustom!=null">
<if test="itemsCustom.name!=null and itemsCustom.name!=''">
items.name LIKE '%${itemsCustom.name}%'
</if>
</if>
</sql>


<!-- 商品的列表查詢
parameterType包裝了查詢條件
resultType使用擴展對象
-->
<select id="findItemsList" parameterType="cn.itcast.ssm.po.ItemsQueryVo" 
resultType="cn.itcast.ssm.po.ItemsCustom">
SELECT * FROM items 
<where>
<include refid="query_items_where"></include>
</where>
</select>


</mapper>



ItemsMapperCustom.java接口
public interface ItemsMapperCustom {


//商品查詢列表
public List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo)throws Exception;
}




定義包裝對象po類
ItemsQueryVo.java 增加set和get方法
public class ItemsQueryVo {


//商品信息包裝進入
private Items items;

//爲了系統可以擴展性,對商品信息定義擴展類
private ItemsCustom itemsCustom;


不使用原始的po類,使用擴展類
ItemsCustom.java
//商品信息的擴展類
public class ItemsCustom extends Items{


//添加商品擴展的屬性
}
==================================================================================
整合service層
讓spring管理service接口。
定義service接口ItemsService.java
//商品管理service
public interface ItemsService {


//商品查詢列表
public List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo)throws Exception;
}


service實現類
ItemsServiceImpl.java
public class ItemsServiceImpl implements ItemsService {


@Autowired
private ItemsMapperCustom itemsMapperCustom;

//itemsMapperCustom直接從service傳到dao
@Override
public List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo) throws Exception {
// TODO Auto-generated method stub
return itemsMapperCustom.findItemsList(itemsQueryVo);
}


}


在spring容器配置service接口
applicationContext-service.xml
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 


xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" 


xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.2.xsd 
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">


<!-- 商品管理的service -->
<bean id="itemsService" class="cn.itcast.ssm.service.impl.ItemsServiceImpl" />
</beans>
事務控制
applicationContext-transation
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 


xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" 


xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.2.xsd 
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">


<!-- 事物管理器
對mybatis操作數據庫事物控制,spring使用jdbc的事物控制類
 -->
 <bean id="transactionManager" 


class="org.springframework.jdbc.datasource.DataSourceTransactionManager" >
  <!-- 配置數據源
  dataSource已經在applicationContext-dao.xml中配置了 -->
  <property name="dataSource" ref="dataSource" />
 </bean>
 
 <!-- 通知 -->
 <tx:advice id="txAdvice" transaction-manager="transactionManager">
  <tx:attributes>
  <!-- 傳播行爲 -->
  <tx:method name="save*" propagation="REQUIRED"/>
  <tx:method name="delete*" propagation="REQUIRED"/>
  <tx:method name="insert*" propagation="REQUIRED"/>
  <tx:method name="update*" propagation="REQUIRED"/>
  <tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
  <tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
  <tx:method name="select*" propagation="SUPPORTS" read-only="true"/>
  </tx:attributes>
 </tx:advice>
 
 <!-- aop -->
 <aop:config>
  <aop:advisor advice-ref="txAdvice" pointcut="execution(* 


cn.itcast.ssm.service.impl.*.*(..))"/>
 </aop:config>
</beans>
=====================================================================================
整合springmvc
創建springmvc.xml
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" 
xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.2.xsd 
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">


<!-- 但是在實際開發中建議使用組件掃描 ,可以掃描controller、service-->
<context:component-scan base-package="cn.itcast.ssm.controller" ></context:component-scan>




<!-- 註解映射器 
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" />-->
<!-- 註解適配器
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" /> -->


<!-- 使用mvc:annotation-driven 代替上邊的註解映射器和註解適配器
mvc:annotation-driven默認加載很多的參數綁定方法,比如json轉換解析器就默認加載了,如果使用mvc:annotation-driven不用配置上邊的RequestMappingHandlerMapping和RequestMappingHandlerAdapter
實際開發使用的也是這個mvc:annotation-driven -->
<mvc:annotation-driven></mvc:annotation-driven>




<!-- 視圖解析器 
解析jsp解析,默認使用jstl標籤,classpath下面得有jstl的包-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 配置jsp路徑的前綴 -->
<property name="prefix" value="/WEB-INF/jsp/" />
<!-- 配置jsp路徑的後綴 -->
<property name="suffix" value=".jsp" />
</bean>


</beans>


配置前端控制器
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_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>springmv_mybatis1208</display-name>
  
  
  <!-- springmvc前段控制器 -->
  <servlet>
  <servlet-name>springmvc</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <!-- contextConfigLocation配置springmvc加載的配置文件(配置處理器映射器、適配器等等) 
  如果不配置contextConfigLocation默認加載/WEB-INF/servlet名稱-servlet.xml(springmvc-


servlet.xml)-->
  <init-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath:spring/springmvc.xml</param-value>
  </init-param>
  </servlet>
  
  <servlet-mapping>
  <servlet-name>springmvc</servlet-name>
  <!-- 第一種:*.action,訪問.action結尾由DispatcherServlet進行解析
  第二種:/,所有訪問的地址都由DispatcherServlet進行解析,對於靜態的文件解析,要配置不讓


DispatcherServlet進行解析
  使用此種方法可以實現RESTful風格的url -->
  <url-pattern>*.action</url-pattern>
  </servlet-mapping>
  
  
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>


編寫Handler(Controller)

ItemsController.java


//使用Controller標識他是一個控制器
@Controller
public class ItemsController {

//注入service
@Autowired
private ItemsService itemsService;


//商品查詢列表
//一般建議將url和方法名寫成一樣,方便queryItems和url進行映射,一個方法對應一個url
@RequestMapping("/queryItems")
public ModelAndView queryItems()throws Exception{
//調用service查找數據庫,查詢商品,這裏先使用靜態模擬
List<ItemsCustom> itemsList = itemsService.findItemsList(null);

//返回ModelAndView
ModelAndView modelAndView = new ModelAndView();
//相當於request的setAttribut,在jsp頁面中通過itemsList取數據
modelAndView.addObject("itemsList",itemsList);

//指定視圖
//下邊的路徑,如果在視圖解析器中配置jsp路徑的前綴和jsp路徑的後綴,就改爲
//modelAndView.setViewName("/WEB-INF/jsp/items/itemsList.jsp");
//上邊的路徑配置可以不再程序中指定jsp路徑的前綴和jsp路徑的後綴
modelAndView.setViewName("items/itemsList");
return modelAndView;
}


編寫jsp

itemsList.jsp


<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"
contentType="text/html; charset=UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>



<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    
    <title>check list</title>
    
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">    
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->


  </head>
  
  <body>
  <form action="${pageContext.request.contextPath }/item/queryItem.action" method="post">
  查詢條件:
  <table width="100%" border=1>
  <tr>
  <td><input type="submit" value="查詢" /></td>
  </tr>
  </table>
  商品列表:
  <table width="100%" border=1>
  <tr>
  <td>商品名稱</td>
  <td>商品價格</td>
  <td>生產日期</td>
  <td>商品描述</td>
  <td>操作</td>
  </tr>
  <c:forEach items="${itemsList }" var="item">
  <tr>
  <td>${item.name }</td>
  <td>${item.price }</td>
  <td><fmt:formatDate value="${item.createtime }" pattern="yyyy-MM-dd HH:mm:ss" /></td>
  <td>${item.detail }</td>
 
  <td><a href="${pageContext.request.contextPath }/editItem.action?id=${item.id}">修改</a></td>
  </tr>
  </c:forEach>
  </table>
  </form>
  </body>
</html>


=====================================================================================
加載spring容器
把dao、service、transaction
建議使用通配符加載上邊的配置文件
在web.xml添加spring容器監聽器,加載spring容器。
<?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_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>springmv_mybatis1208</display-name>
  
  <!-- 加載spring容器 
  <param-value>/WEB-INF/classes/spring/applicationContext.xml,/WEB-


INF/classes/spring/applicationContext-*.xml</param-value>-->
  <context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>/WEB-INF/classes/spring/applicationContext-*.xml</param-value>
  </context-param>
  <listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章