記錄ssm整合(xml + 註解)
開發環境:
jdk 1.8 tomcat 7 eclipse4.8 spring 4.3 mysql 5.1.29 myBatis 3.4
準備工作(創建數據表):
1.先整合springmvc
1.1 搭建目錄,導入jar包
1.2 在 web.xml 中配置核心控制器,在spring-mvc-4.3.16.jar中,找到 DispatcherServlet ,右鍵復制路徑
<?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" id="WebApp_ID" version="3.0"> <display-name>ssm</display-name> <servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> </web-app>
1.3 在Student實體類中編寫成員屬性 Student.java
package cn.demo.pojo; public class Student { private Long stuId; private String stuName; private String stuPassword; private Integer stuAge; public Long getStuId() { return stuId; } public void setStuId(Long stuId) { this.stuId = stuId; } public String getStuName() { return stuName; } public void setStuName(String stuName) { this.stuName = stuName; } public String getStuPassword() { return stuPassword; } public void setStuPassword(String stuPassword) { this.stuPassword = stuPassword; } public Integer getStuAge() { return stuAge; } public void setStuAge(Integer stuAge) { this.stuAge = stuAge; } }
1.4 StudentController.java
在 insert 方法裏接收 Student 對象,為了後面整合 mybatis 。
package cn.demo.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import cn.demo.pojo.Student; @Controller @RequestMapping(value="/student") // 作用相當於namespace public class StudentController { @RequestMapping(value="insert.do", method=RequestMethod.POST) // 只接收post請求 public String insert(Student student) { return "/jsp/student-list.jsp"; } }
1.5 在項目根目錄下創建 source folder 源文件夾 config,作用等同於 src,即classpath路徑下。用來存放 spring 等xml配置文件。
1.6 在 config 文件夾下創建 spring-context.xml 和 spring-mvc.xml。在 spring-context.xml 中開啟掃描組件掃描指定包下的類。在 spring-mvc-xml 中,需要告知Spring,啟用註解驅動,然後Spring會將其註冊到bean中。
spring-context.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:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd"> <context:component-scan base-package="cn.demo"></context:component-scan> </beans>
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:mvc="http://www.springframework.org/schema/mvc" 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-4.3.xsd"> <mvc:annotation-driven></mvc:annotation-driven> </beans>
1.7 接下來要在 web.xml 中配置 contextConfigLocation 屬性,在 web 服務器啟動的時候就啟動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_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>ssm</display-name> <servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-*.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> </web-app>
contextConfigLocation 屬性在 DispatcherServlet 它爹 FrameworkServlet中找到
...FrameworkServlet.java
1.8 在 index.jsp 編寫表單,表單裏的name屬性要跟實體類的成員屬性對應,因為spring根據set方法註入。
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <form action="${pageContext.request.contextPath }/student/insert.do" method="post"> username: <input type="text" name="stuName"/><br> password: <input type="password" name="stuPassword"/><br> age: <input type="text" name="stuAge"/><br> <input type="submit" value="提交"/> </form> </body> </html>
1.9 然後在 student-list.jsp 中先隨便寫點內容(因為我們controller 裏 insert 方法跳轉的頁面是它,現在測試是否成功整合springmvc)
然後開啟服務器,訪問 index.jsp,成功跳轉 student-list.jsp 即整合springmvc成功。
2. 開始整合 mybatis
2.1 依舊是導包
2.2 現創建如下目錄
2.3 編寫接口文件和映射文件
StudentMapper.java
package cn.demo.mapper; import cn.demo.pojo.Student; public interface StudentMapper { public Integer insert(Student student); }
StudentMapper.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "mybatis-3-mapper.dtd" > <mapper namespace="cn.demo.mapper.StudentMapper"> <insert id="insert"> insert into tb_student(stu_name,stu_password,stu_age) values(#{stuName},#{stuPassword},#{stuAge}) </insert> </mapper>
2.4 在config文件夾下創建 spring-data.xml,這裏是 mybatis 相關操作
2.5 spring-data.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:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd"> <!-- 1. 配置數據源 --> <bean name="dataSource" class="org.apache.commons.dbcp2.BasicDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/hibernate"/> <property name="username" value="root"/> <property name="password" value="root"/> </bean> <!-- 2. 配置session工廠 --> <bean name="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <!-- 如果有映射文件配置映射文件的路徑 --> <property name="mapperLocations" value="classpath:cn/demo/mapper/xml/*Mapper.xml"/> <!-- mybatis參數 --> <!-- 別名設置,在這個包下的都可以用別名 --> <property name="typeAliasesPackage" value="cn.demo.pojo"/> <!-- 駝峰命名 --> <property name="configuration"> <bean class="org.apache.ibatis.session.Configuration"> <property name="mapUnderscoreToCamelCase" value="true"/> </bean> </property> </bean> <!-- 3. 配置映射接口的配置器,用於創建映射接口的動態對象,並註入到spring容器裏--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 指定會話工廠 --> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactoryBean"></property> <!-- 指定掃描映射接口的位置 --> <property name="basePackage" value="cn.demo.mapper"></property> </bean> </beans>
2.6 在 config 文件夾下創建 log4j 配置文件 log4j.properties 輸出運行日誌
log4j.rootLogger=DEBUG, A1
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-4r %-5p [%t] %37c %3x - %m%n
log4j.logger.org.springframework=ERROR
2.7 StudentService.java
package cn.demo.service; import cn.demo.pojo.Student; public interface StudentService { public Integer insert(Student student); }
2.8 StudentServiceImpl.java
package cn.demo.service.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import cn.demo.mapper.StudentMapper; import cn.demo.pojo.Student; import cn.demo.service.StudentService; @Service public class StudentServiceImpl implements StudentService{ @Autowired private StudentMapper studentMapper; @Override public Integer insert(Student student) { Integer count = studentMapper.insert(student); return count; } }
2.9 訪問index.jsp, 輸入內容,會看到 log4j 的輸出信息,數據已成功插入數據表中
2.10 亂碼問題解決,在 web.xml 中添加編碼過濾器(spring內置)
<!-- 編碼過濾器 --> <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>
3. 配置事務
在 web.xml 中添加如下配置
<!-- 4.配置事務代理 --> <bean name="tm" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!-- 指定事務代理的數據源 --> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 5.啟動事務代理,聲明式事務 --> <tx:annotation-driven transaction-manager="tm"/>
完整的 spring-data.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:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" 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/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd"> <!-- 1. 配置數據源 --> <bean name="dataSource" class="org.apache.commons.dbcp2.BasicDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/hibernate"/> <property name="username" value="root"/> <property name="password" value="root"/> </bean> <!-- 2. 配置session工廠 --> <bean name="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <property name="mapperLocations" value="classpath:cn/lz/mapper/*Mapper.xml"></property> <property name="configuration"> <bean class="org.apache.ibatis.session.Configuration"> <property name="mapUnderscoreToCamelCase" value="true"></property> </bean> </property> </bean> <!-- 3.掃描mapper接口,生成mapper接口代理 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactoryBean" ></property> <property name="basePackage" value="cn.lz.mapper"></property> </bean> <!-- 4.配置事務代理 --> <bean name="tm" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!-- 指定事務代理的數據源 --> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 5.啟動事務代理,聲明式事務 --> <tx:annotation-driven transaction-manager="tm"/> </beans>View Code
!關於事務代理的註意事項
Spring 是通過拋出異常來判斷事務是否回滾的。
所以事務代理的操作中不可以捕獲異常,異常必須要拋到上一層處理。
ok 終於完了……
記錄ssm整合(xml + 註解)