在整合Spring,SpringMVC 和 MyBatis 的過程當中,很容易遇到一些小問題,所以記錄下整合過程。html
首先是安裝環境和開發工具,以下:java
整個項目在Maven WebApp模板工程的基礎上構建,不一樣類型的文件放置於不一樣的包或者路徑下,所有配置完成後的工程結構以下圖所示:mysql
不一樣路徑下的文件歸類說明以下表(classpath至關於resources文件夾):git
包名/路徑名 | 做用 |
---|---|
controller | 存放控制器 |
mapper | DAO層接口 |
pojo | 實體類 |
service | 業務類(接口+實現) |
/com/cr/mapper | 對應mapper下接口的xml文件 |
/spring | 與spring相關的配置文件 |
/webapp/jsp | 存放jsp文件 |
/*.properties | 資源文件 |
pom.xmlgithub
<?xml version="1.0" encoding="UTF-8"?> <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/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.cr</groupId> <artifactId>SSMTest</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <name>SSMTest Maven Webapp</name> <!-- FIXME change it to the project's website --> <url>http://www.example.com</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> <spring.version>5.0.8.RELEASE</spring.version> <jackson.version>2.9.3</jackson.version> </properties> <dependencies> <!--添加Spring MVC的依賴--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <!--添加Servlet的依賴--> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <!--JSTL用於在控制器中將模型綁定到JSP中--> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!--添加spring的依賴--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</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-jdbc</artifactId> <version>${spring.version}</version> </dependency> <!--利用它處理事務問題--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <!--添加數據庫Mysql驅動--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <!--驅動版本號必定要裝正確 不然連不上 mysql 5.1.46 能夠適用本機--> <version>5.1.46</version> </dependency> <!--添加Mybatis依賴--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.2.6</version> </dependency> <!--整合Mybatis與Spring的依賴--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.0</version> </dependency> <!-- Mybatis分頁依賴 --> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>5.1.2</version> </dependency> <!-- 處理時間日期格式 --> <dependency> <groupId>joda-time</groupId> <artifactId>joda-time</artifactId> <version>2.9.9</version> </dependency> <!-- 用於MD5加密 --> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.10</version> </dependency> <!--日誌--> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.12</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.12</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <!--添加Json依賴--> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>${jackson.version}</version> </dependency> <!--有時候不加可能會報錯--> <dependency> <groupId>net.sf.json-lib</groupId> <artifactId>json-lib</artifactId> <version>2.4</version> <classifier>jdk15</classifier> </dependency> <!-- 新添加處理json爲java bean --> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-core-asl</artifactId> <version>1.9.13</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency> <!-- 文件上傳 高版本可使用Multipart解析器 就不用引入這個包了 --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <!-- 數據源的引入, 池化技術 --> <dependency> <groupId>com.mchange</groupId> <artifactId>c3p0</artifactId> <version>0.9.2.1</version> </dependency> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.2.2</version> </dependency> </dependencies> <build> <finalName>SSMTest</finalName> <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) --> <plugins> <plugin> <artifactId>maven-clean-plugin</artifactId> <version>3.0.0</version> </plugin> <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging --> <plugin> <artifactId>maven-resources-plugin</artifactId> <version>3.0.2</version> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.7.0</version> </plugin> <plugin> <artifactId>maven-surefire-plugin</artifactId> <version>2.20.1</version> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>3.2.0</version> </plugin> <plugin> <artifactId>maven-install-plugin</artifactId> <version>2.5.2</version> </plugin> <plugin> <artifactId>maven-deploy-plugin</artifactId> <version>2.8.2</version> </plugin> </plugins> </pluginManagement> </build> </project>
添加完成後的maven依賴以下:web
spring上下文文件路徑配置spring
<!--配置Spring IoC的配置文件路徑 classpath至關於resources文件夾--> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/applicationContext.xml</param-value> </context-param>
這裏指定了上下文配置文件爲spring文件夾下的applicationContext.xml,稍後再配置這個文件。sql
Log4j配置數據庫
<context-param> <param-name>log4jRefreshInterval</param-name> <param-value>60000</param-value> </context-param>
ContextLoaderListener監聽器配置apache
<listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 防止Spring內存溢出監聽器 --> <listener> <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener>
DispatcherServlet前置控制器配置
<servlet> <!--springmvc框架默認自動找到/WEB-INF/springmvc-servlet.xml做爲配置文件載入web工程中 這裏手動設置位置--> <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/springmvc-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> <async-supported>true</async-supported> </servlet>
springmvc框架默認自動找到/WEB-INF/[servlet-name]-servlet.xml做爲配置文件載入web工程中 這裏手動設置位置爲spring文件夾下的springmvc-servlet.xml,稍後再配置這個文件。
Servlet攔截設置
<servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <!-- Spring配置 --> <!-- ================================================= --> <!--配置Spring IoC的配置文件路徑 classpath至關於resources文件夾--> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/applicationContext.xml</param-value> </context-param> <!--Log4j配置--> <context-param> <param-name>log4jRefreshInterval</param-name> <param-value>60000</param-value> </context-param> <!--配置ContextLoaderListener初始化IOC容器--> <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配置 --> <!-- ================================================= --> <!--DispatcherServlet前置控制器配置--> <servlet> <!--springmvc框架默認自動找到/WEB-INF/springmvc-servlet.xml做爲配置文件載入web工程中 這裏手動設置位置--> <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/springmvc-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> <async-supported>true</async-supported> </servlet> <!--攔截內容:servlet映射設置--> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
applicationContext.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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!--引入spring和其餘整合的配置文件 好比spring-mybatis.xml等--> <import resource="classpath:spring/spring-*.xml"/> </beans>
配置自動掃描,須要掃描到控制層和服務層,剛開始我這裏寫成了com.cr.mapper,結果致使控制器不能注入
<context:component-scan base-package="com.cr" />
新建數據庫資源文件jdbc.properties,針對不一樣的數據庫須要修改配置 同時要注意匹配數據庫的版本號,好比我安裝的是MySQL 8.0,以前因爲驅動版本弄錯了,因此老是鏈接數據庫失敗,後來改爲5.1.46才解決了問題
# 針對不一樣的數據庫須要修改配置 同時要注意匹配數據庫的版本號 mysql.driver=com.mysql.jdbc.Driver mysql.url=jdbc:mysql://localhost:3306/mybatis mysql.username=root mysql.password=XXXX #定義初始鏈接數 dbcp.initialSize=0 #定義最大鏈接數 dbcp.maxActive=20 #定義最大空閒 dbcp.maxIdle=20 #定義最小空閒 dbcp.minIdle=1 #定義最長等待時間 dbcp.maxWait=60000
引入數據庫資源文件
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:jdbc.properties" /> </bean>
配置數據庫MySQL
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="${mysql.driver}" /> <property name="url" value="${mysql.url}" /> <property name="username" value="${mysql.username}" /> <property name="password" value="${mysql.password}" /> <property name="initialSize" value="${dbcp.initialSize}" /> <property name="maxActive" value="${dbcp.maxActive}" /> <property name="maxIdle" value="${dbcp.maxIdle}" /> <property name="minIdle" value="${dbcp.minIdle}" /> <property name="maxWait" value="${dbcp.maxWait}" /> </bean>
整合Spring和MyBatis,注意路徑的書寫方式是"/"不是"."
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 自動掃描mapping.xml文件 注意路徑是"/"不是"."--> <property name="mapperLocations" value="classpath:com/cr/mapper/*.xml" /> <property name="configuration"> <!--能夠將以前mybatis.cfg.xml的一些配置項轉移到這裏來--> <bean class="org.apache.ibatis.session.Configuration"> <property name="mapUnderscoreToCamelCase" value="true" /> </bean> </property> </bean>
掃描持久層接口
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.cr.mapper" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> </bean>
數據庫事務管理
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean>
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" xmlns:tx="http://www.springframework.org/schema/cache" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.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 http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 自動掃描包 包括了控制層和服務層 --> <context:component-scan base-package="com.cr" /> <!-- 引入數據庫配置文件 --> <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"> <property name="driverClassName" value="${mysql.driver}" /> <property name="url" value="${mysql.url}" /> <property name="username" value="${mysql.username}" /> <property name="password" value="${mysql.password}" /> <property name="initialSize" value="${dbcp.initialSize}" /> <property name="maxActive" value="${dbcp.maxActive}" /> <property name="maxIdle" value="${dbcp.maxIdle}" /> <property name="minIdle" value="${dbcp.minIdle}" /> <property name="maxWait" value="${dbcp.maxWait}" /> </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/cr/mapper/*.xml" /> <property name="configuration"> <!--能夠將以前mybatis.cfg.xml的一些配置項轉移到這裏來--> <bean class="org.apache.ibatis.session.Configuration"> <property name="mapUnderscoreToCamelCase" value="true" /> </bean> </property> </bean> <!-- 掃描DAO持久層接口 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.cr.mapper" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> </bean> <!-- 數據庫事務管理 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> </beans>
springmvc-servlet.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" xmlns:mvc="http://www.springframework.org/schema/mvc" 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-4.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd"> <!-- scan the package and the sub package --> <context:component-scan base-package="com.cr.controller"/> <!-- don't handle the static resource --> <mvc:default-servlet-handler /> <!-- if you use annotation you must configure following setting --> <mvc:annotation-driven /> <!-- configure the InternalResourceViewResolver --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver"> <!--至關於尋找/jsp/xxx.jsp文件--> <!-- 前綴 --> <property name="prefix" value="/jsp/" /> <!-- 後綴 --> <property name="suffix" value=".jsp" /> </bean> </beans>
alt
+ insert
生成 setter和getter方法User.java
package com.cr.pojo; public class User { private String username; private String password; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
建立測試用表t_user,並添加兩條數據
在mapper包下新建一個UserMapper接口,包含一個select查詢方法,能夠查詢用戶是否存在,若不存在返回null
UserMapper.java
package com.cr.mapper; import com.cr.pojo.User; public interface UserMapper { User select(User user); }
建立UserMapper和mybatis映射文件 UserMapper.xml,路徑是resource/com/cr/mapper
UserMapper.xml
<?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="com.cr.mapper.UserMapper"> <select id="select" parameterType="com.cr.pojo.User" resultType="com.cr.pojo.User"> select * from t_user where username = #{username} and password = #{password} </select> </mapper>
創建UserService接口,位於service包下
UserService.java
package com.cr.service; import com.cr.pojo.User; public interface UserService { /** * 根據user信息檢查數據庫中是否存在該用戶 */ User get(User user); }
在service包下創建impl子包,添加實現類UserServiceImpl
UserServiceImpl.java
package com.cr.service.impl; import com.cr.mapper.UserMapper; import com.cr.pojo.User; import com.cr.service.UserService; import org.springframework.stereotype.Service; import javax.annotation.Resource; // @Service用於業務層 功能等同於@component @Service("userService") public class UserServiceImpl implements UserService { @Resource private UserMapper userMapper; @Override public User get(User user) { // 經過Mapper的select方法查詢用戶 return userMapper.select(user); } }
UserController.java
package com.cr.controller; import com.cr.pojo.User; import com.cr.service.UserService; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import javax.annotation.Resource; // spring-mybatis.xml和springmvc-servlet.xml都配置了掃描控制層 @Controller public class UserController { // 注入UserService @Resource private UserService userService; @RequestMapping(value = "/login") public String login(User user) { ModelAndView mv = new ModelAndView(); System.out.println("開始查詢---"); user = userService.get(user); if (user != null) { System.out.println("查到的User: " + user.getUsername()); mv.addObject("user", user); // 轉到user.jsp用戶界面 return "user"; } else { System.out.println("未查到此用戶"); // 查不到用戶信息,則重定向回登陸界面 System.out.println("重定向回登陸界面---"); return "login"; } } }
login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>login</title> </head> <body> <h1>用戶登陸界面</h1> <h2>用戶信息</h2> <h3>Tom 123</h3> <h3>Jack 456</h3> <br> <form id="form" action="/login" method="post"> <table> <tr> <td>用戶名</td> <td><input id="username" name="username" value="" /></td> </tr> <tr> <td>密碼</td> <td><input id="password-always-checkbox" name="password" /></td> </tr> <tr> <td></td> <td align="right"><input type="submit" value="提交"></td> </tr> </table> </form> </body> </html>
user.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>User</title> </head> <body> <h1>用戶登陸成功</h1> <br> 歡迎您: ${user} </body> </html>
瀏覽器訪問http://localhost:8080/login
填寫錯誤的用戶名或者密碼,瀏覽器將從新返回登陸界面,控制檯顯示以下:
填寫正確的用戶名Tom和密碼123,跳轉到登陸成功界面user.jsp,顯示以下:
以上說明SSM框架整合成功,項目地址:https://github.com/wychencr/SSM-Test
MySQL的驅動要匹配本機安裝的版本
resources文件夾要被標記爲Resource Root
xml配置文件中的classpath至關於/resources
IDEA可能會提示上下文配置文件沒有添加,只要打開工程結構選項,把當前xml文件添加到工程中便可
注意各個xml配置文件中掃描包的位置,若是有遺漏就會報錯
注意各個jar包的版本問題,我原來使用最新的Mybatis 3.4.6就會出現報錯
java.lang.IllegalAccessError: org.apache.commons.dbcp.DelegatingPreparedStatement.isClosed()
修改版本爲3.2.6後解決問題
歡迎訪問個人我的博客: https://chenran.tk/