SSM集成
?
1.?Spring和各個框架的整合
?
Spring目前是JavaWeb開發中最終的框架,提供一站式服務,可以其他各個框架整合集成
?
Spring整合方案
?
1.1.?SSH
ssh是早期的一種整合方案
Struts2 : Web層框架
Spring : 容器框架
Hibernate : 持久層框架
?
2.?SSM
主流的項目架構的三大框架(相對其他框架而言,最優秀)
?SpringMVC : spring自己家的 Web層框架,spring的一個模塊
?Spring :容器框架
?MyBatis :持久層框架
?
?
3.?Spring與MyBatis整合
3.1.?集成思路
實際開發,使用Maven項目,直接引入項項目在Maven倉庫中的坐標即可
?
學習階段: 手動導入jar包,從零開始集成(鞏固基礎知識)
?
3.2.?創建java項目
? ? |
?
3.3.?準備集成相關jar包
3.3.1.?Spring依賴包
? ? |
3.3.2.?SpringMVC依賴包
? ? |
?
3.3.3.?Mybatis依賴包
? ? |
3.3.4.?MyBatis和Spring框架集成的橋梁包
Spring自己并沒有集成MyBatis框架,需要MyBatis自己來集成,所以需要自己提供Spring框架集成的橋梁包
?
如果我們使用的mybatis3.4.4 不能直接使用mybatis內置的 橋梁包版本,版本比較低,無法正常運行,需要單獨下載一個比價高的版本
? ? |
3.3.5.?數據庫驅動包和連接池
? ? |
? ? |
?
3.3.6.?Jstl標簽庫依賴包
? ? |
?
3.3.7.?Mybatis支持的日志包log4j
? ? |
3.4.?項目集成需要各種配置文件
? ? |
?
3.5.?Mapper層
package?cn.zj.ssm.mapper; ? import?java.util.List; ? import?cn.zj.ssm.pojo.User; ? public?interface?UserMapper { ? int?insert(User user); ? User selectByPrimaryKey(Integer id); ? ? List<User> selectList(); ? int?delteByPrimaryKey(Integer id); } ? |
?
3.5.1.?Mapperxml文件
<?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.zj.ssm.mapper.UserMapper"> ? <insert?id="insert"?parameterType="cn.zj.ssm.pojo.User"> insert into user (name,password,age)values(#{name},#{password},#{age}) </insert> ? <select?id="selectByPrimaryKey"?parameterType="Integer"?resultType="cn.zj.ssm.pojo.User"> select * from user where id = #{id} </select> ? <select?id="selectList"??resultType="cn.zj.ssm.pojo.User"> select * from user </select> ?? ?? <delete?id="delteByPrimaryKey"?parameterType="int"> ?? delete from user where id = #{id} ?? </delete> ?? </mapper> |
?
3.6.?完成項目層與層之間spring對象的創建和依賴關系的維護
3.6.1.?Service層
package?cn.zj.ssm.service.impl; ? import?java.util.List; ? import?org.springframework.beans.factory.annotation.Autowired; import?org.springframework.stereotype.Service; ? import?cn.zj.ssm.mapper.UserMapper; import?cn.zj.ssm.pojo.User; import?cn.zj.ssm.service.UserService; ? @Service public?class?UserServiceImpl implements?UserService { /* ?* 問題: UserMapper 代理對象如何創建? ?* 答 :使用 SqlSession 操作對象創建 ! ?* ?* 問題 : SqlSession 對象如何創建? ?* ? ?* 答 : SqlSessionFactory 工廠對象創建? ?* ?* 問題: SqlSessionFactory 對象如何創建 ?* ?* 1,和Spring框架集成之前 ?* ?MyBatis框架自己讀取配置文件中的相關配置去創建 ?* 2, 和Spring框架集成之后 ?* ?交個Spring容器來創建 ?* 問題: 如何在Spring框架中配置,創建出來SqlSessionFactory對象? ?* ?mybatis和spring集成的類查閱 橋梁包 ?* ?org.mybatis.spring.SqlSessionFactoryBean 創建 SqlSessionFactory ?* ?*/ @Autowired private?UserMapper mapper; ? @Override public?int?insert(User user) { return?mapper.insert(user); } ? @Override public?User selectByPrimaryKey(Integer id) { System.out.println(mapper); return?mapper.selectByPrimaryKey(id); } ? @Override public?List<User> selectList() { return?mapper.selectList(); } ? @Override public?int?delteByPrimaryKey(Integer id) { return?mapper.delteByPrimaryKey(id); } ? ? ? } ? |
3.6.2.?測試代碼
package?cn.zj.ssm.test; ? import?java.util.List; ? import?org.junit.Test; import?org.junit.runner.RunWith; import?org.springframework.beans.factory.annotation.Autowired; import?org.springframework.test.context.ContextConfiguration; import?org.springframework.test.context.junit4.SpringJUnit4ClassRunner; ? import?cn.zj.ssm.pojo.User; import?cn.zj.ssm.service.UserService; ? @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:spring.xml") public?class?UserServiceTest { ? @Autowired private?UserService service; ? @Test public?void?testInsert() { User user?= new?User(null, "喬峰", "qiaofeng", 30); int?row?= service.insert(user); System.out.println(row); ? } ? @Test public?void?testSelectByPrimaryKey() { User user?= service.selectByPrimaryKey(8); System.out.println(user); } ? @Test public?void?testSelectList() throws?Exception { List<User> users?= service.selectList(); ? for?(User user?: users) { System.out.println(user); } } ? } ? |
?
3.6.3.?applicationContext配置文件的配置
<?xml?version="1.0"?encoding="UTF-8"?> <beans?xmlns="http://www.springframework.org/schema/beans" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" ????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.xsd ????????http://www.springframework.org/schema/aop ????????http://www.springframework.org/schema/aop/spring-aop.xsd ????????http://www.springframework.org/schema/tx ????????http://www.springframework.org/schema/tx/spring-tx.xsd ????????"> ? ? <!-- 設置注解配置包掃描位置 --> <context:component-scan base-package="cn.zj.mybatis"/> ? </beans> |
?
3.7.?MyBatis 框架SqlSessionFactory對象的創建
?
?* 問題: UserMapper 代理對象如何創建?
?* 答 :使用 SqlSession 操作對象創建 !
?*
?* 問題 : SqlSession 對象如何創建?
?* ?
?* 答 : SqlSessionFactory 工廠對象創建?
?*
?* 問題: SqlSessionFactory 對象如何創建
?*
?* 1,和Spring框架集成之前
?* ?MyBatis框架自己讀取配置文件中的相關配置去創建
?* 2, 和Spring框架集成之后
?* ?交個Spring容器來創建
?* 問題: 如何在Spring框架中配置,創建出來SqlSessionFactory對象?
?* ?mybatis和spring集成的類查閱 橋梁包
?* ?org.mybatis.spring.SqlSessionFactoryBean 創建 SqlSessionFactory
?*
?*/
創建MyBatis框架工廠對象的 類在mybatis-spring1.2.1.jar 橋梁包中的
org.mybatis.spring.SqlSessionFactoryBean?類 如下圖
? ? |
?
3.7.1.?配置文件
<?xml?version="1.0"?encoding="UTF-8"?> <beans?xmlns="http://www.springframework.org/schema/beans" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" ????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.xsd ????????http://www.springframework.org/schema/aop ????????http://www.springframework.org/schema/aop/spring-aop.xsd ????????http://www.springframework.org/schema/tx ????????http://www.springframework.org/schema/tx/spring-tx.xsd ????????"> ? ? <!-- 配置讀取 db.properties 數據庫配置文件 --> <context:property-placeholder?location="classpath:db.properties"/> ? <!-- 配置數據源連接池 --> <bean?id="dataSource"?class="com.alibaba.druid.pool.DruidDataSource"?init-method="init"?destroy-method="close"> <property?name="driverClassName"?value="${jdbc.driverClassName}"/> <property?name="url"?value="${jdbc.url}"/> <property?name="username"?value="${jdbc.username}"/> <property?name="password"?value="${jdbc.password}"/> <property?name="maxActive"?value="${jdbc.maxActive}"/> </bean> ? ? <!-- 配置MyBatis框架的 SqlSessionFactoryBean 類,創建 ? ?SqlSessionFactory 工廠對象 ?--> <bean?id="sqlSessionFactory"?class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 1.注入數據源 --> <property?name="dataSource"?ref="dataSource"/> ? ? <!-- 2.配置映射文件 --> <property?name="mapperLocations"> <array> <!-- <value>classpath:cn/zj/mybatis/mapper/UserMapper.xml</value> --> <!-- 可以使用通配符 * 讀取 目錄下面所有的配置文件 --> <value>classpath:cn/zj/mybatis/mapper/*Mapper.xml</value> </array> </property> ? <!-- 3. 配置別名使用包掃描 --> <property?name="typeAliasesPackage"?value="cn.zj.mybatis.pojo"/> ? <!-- 4.讀取mybat-config.xml配置文件,此配置文件可能還會配一些mybatis框架的 其他個性化配置 實際項目開發可能不用配置 ?--> ?<property?name="configLocation"?value="classpath:mybatis-config.xml"/> </bean> </beans> |
3.8.?創建MyBatis的Mapper接口的代理對象
使用橋梁包 org.mybatis.spring.mapper.MapperFactoryBean<T> 創建 UserMapper代理對象
? ? |
?
此種方式每一個Mapper接口需要單獨配置,如果Mapper過多,創建Mapper可能造成配置代碼過多
?? ?<!-- 創建UserMapper代理對象-創建單個Mapper對象 ??? ?使用橋梁包 org.mybatis.spring.mapper.MapperFactoryBean<T> 創建 UserMapper代理對象 ??--> ?? ??<bean?id="userMapper"?class="org.mybatis.spring.mapper.MapperFactoryBean"> ?? ?? <!-- 注入SqlSessionFacotry對象 --> ?? <property?name="sqlSessionFactory"?ref="sqlSessionFactory"/> ?? ?? <!-- 注入UserMapper接口類型:底層創建UserMapper的代理對象 --> ?? <property?name="mapperInterface"?value="cn.zj.mybatis.mapper.UserMapper"/> ?? ??</bean> |
?
?
3.9.?使用包掃描創建MyBatis的Mapper接口的代理對象
? ? |
?
?
<!-- 批量創建Mapper代理對象 ,使用包掃描創建Mapper代理對象 ??使用橋梁包 ??org.mybatis.spring.mapper.MapperScannerConfigurer ??--> ?? ??<bean?class="org.mybatis.spring.mapper.MapperScannerConfigurer"> ?? <!-- 配置需要創建Mapper接口代理對象對應的包 --> ?? <property?name="basePackage"?value="cn.zj.mybatis.mapper"/> ?? ?? <!-- 配置SqlSessionFactoryBean 的名稱,不是引用 --> ?? <property?name="sqlSessionFactoryBeanName"?value="sqlSessionFactory"/> ??</bean> |
?
3.10.?MyBatis的事務管理器的配置
一般開發,事務的管理都會使用aop切入到業務層
?
??<!-- 配置事務管理器 --> ??<bean?id="transactionManager"?class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> ?? <!-- 注入數據源 --> ?? <property?name="dataSource"?ref="dataSource"/> ??</bean> ?? ??<!-- spring事務配置 --> ??<tx:advice?id="txAdvice"?transaction-manager="transactionManager"> ?? ?? <!-- 事務屬性配置 --> ?? <tx:attributes> ?? <!-- DQL :查詢操作,配置只讀事務 --> ?? <tx:method?name="get*"?read-only="true"?isolation="REPEATABLE_READ"??propagation="REQUIRED"/> ?? <tx:method?name="select*"?read-only="true"?isolation="REPEATABLE_READ"??propagation="REQUIRED"/> ?? <tx:method?name="find*"?read-only="true"?isolation="REPEATABLE_READ"??propagation="REQUIRED"/> ?? <tx:method?name="query*"?read-only="true"?isolation="REPEATABLE_READ"??propagation="REQUIRED"/> ?? ?? <!-- 其他 SQL :非只讀事務 --> ?? <tx:method?name="*"?read-only="false"?isolation="REPEATABLE_READ"??propagation="REQUIRED"/> ?? ?? </tx:attributes> ?? ??</tx:advice> ?? ??<!-- 配置AOP 切入事務 --> ?? ??<aop:config> ?? <!-- 切入點 --> ?? <aop:pointcut?expression="execution(* cn.zj.mybatis.service..*.*(..))"?id="pt"/> ?? ?? <!-- 切面 --> ?? <aop:advisor?advice-ref="txAdvice"?pointcut-ref="pt"/> ??</aop:config> ? |
?
4.?SpringMVC的集成
4.1.?在在web.xml配置SpringMVC的前端控制器
<?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"> ? <!-- 配置字符編碼過濾器 --> <filter> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> ? ? <!-- 配置前端控制器 --> <servlet> <servlet-name>MVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> ? <!-- 讀取配置文件 問題:有多個spring相關配置文件如何讀取 如 :spring.xml 和springmvc.xml ? 解決方案: 方案一:直接使用 統配 * 可以讀取多個有相同前綴的文件 <param-value>classpath:spring*.xml</param-value> 方案二:先讀取一個配置文件 如果 spring.xml 再在spring.xml文件中使用<import>標簽導入 springmvc.xml文件 <import resource="classpath:springmvc.xml"/> ?--> ? <param-value>classpath:spring.xml</param-value> </init-param> ? <load-on-startup>1</load-on-startup> ? </servlet> <servlet-mapping> <servlet-name>MVC</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> ? </web-app> |
4.1.1.?springmvc.xml配置文件
<?xml?version="1.0"?encoding="UTF-8"?> <beans?xmlns="http://www.springframework.org/schema/beans" xmlns:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans ????????http://www.springframework.org/schema/beans/spring-beans.xsd ????????http://www.springframework.org/schema/mvc ????????http://www.springframework.org/schema/mvc/spring-mvc.xsd ????????"> <!-- 配置springmvc的注解驅動 --> <mvc:annotation-driven/> ? </beans> |
?
?
4.2.?編寫控制器 UserController
package?cn.zj.ssm.controller; ? import?java.util.List; ? import?org.springframework.beans.factory.annotation.Autowired; import?org.springframework.stereotype.Controller; import?org.springframework.ui.Model; import?org.springframework.web.bind.annotation.RequestMapping; ? import?cn.zj.ssm.pojo.User; import?cn.zj.ssm.service.UserService; ? @Controller @RequestMapping("/user") public?class?UserController { ? @Autowired private?UserService service; ? @RequestMapping("/list") public?String list(Model m) { ? //調用service查詢所有用戶方法 List<User> users?= service.selectList(); ? //共享數據 m.addAttribute("users", users); ? return?"/WEB-INF/view/user_list.jsp"; } ? ? @RequestMapping("/delete") public?String delete(Integer id) { System.out.println(id); ? //調用service層的刪除方法 service.delteByPrimaryKey(id); ? return?"redirect:/user/list.do"; } ? } ? |
?
4.3.?user_list.jsp 頁面
在jsp頁面 使用jstl標簽庫需要先在頁面引入jstl 標簽庫
<%@?page?language="java"?contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!-- 引入jstl標簽庫 ?--> <%@?taglib?uri="http://java.sun.com/jsp/jstl/core"?prefix="c"%> <!DOCTYPE?html> <html> <head> <meta?charset="UTF-8"> <title>Insert title here</title> </head> <body> <h3>用戶列表</h3> ? <table?border="1"?style="width: 500px;" cellspacing="0"> <tr> <th>id</th> <th>名稱</th> <th>密碼</th> <th>年齡</th> <th>操作</th> </tr> ? ? <c:forEach?items="${users}"?var="user"> <tr> <td>${user.id}</td> <td>${user.name}</td> <td>${user.password}</td> <td>${user.age}</td> <td> <a?href="javascript:void(0);"?οnclick="deleteByPrimaryKey(${user.id})">刪除</a>??? <a?href="">修改</a> </td> </tr> </c:forEach> </table> ? <script?type="text/javascript"> ? function?deleteByPrimaryKey(userId){ ? if(confirm("親,您確定刪除此條數據么?")){ window.location.href= "${pageContext.request.contextPath}/user/delete.do?id="+userId; } } ? </script> ? </body> </html> |