2020最新版SSM框架整合教程
實驗環(huán)境為:IDEA2020.1+MySQL8.0.21+Tomcat9.0.36+Maven3.3.9
最終項目結(jié)構(gòu)圖:
一、搭建數(shù)據(jù)庫環(huán)境
創(chuàng)建一個存放書籍?dāng)?shù)據(jù)的數(shù)據(jù)庫表
CREATE DATABASE `ssmbuild`; USE `ssmbuild`; DROP TABLE IF EXISTS `books`; CREATE TABLE `books` ( `bookID` INT(10) NOT NULL AUTO_INCREMENT COMMENT '書id', `bookName` VARCHAR(100) NOT NULL COMMENT '書名', `bookCounts` INT(11) NOT NULL COMMENT '數(shù)量', `detail` VARCHAR(200) NOT NULL COMMENT '描述', KEY `bookID` (`bookID`) ) ENGINE=INNODB DEFAULT CHARSET=utf8 INSERT INTO `books`(`bookID`,`bookName`,`bookCounts`,`detail`)VALUES (1,'Java',1,'從入門到放棄'), (2,'MySQL',10,'從刪庫到跑路'), (3,'Linux',5,'從進(jìn)門到進(jìn)牢');
生成表格:
二、基本環(huán)境搭建
1、創(chuàng)建maven項目,添加web支持
2、導(dǎo)入依賴
<dependencies> <!--Junit--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13</version> </dependency> <!--數(shù)據(jù)庫驅(qū)動--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.21</version> </dependency> <!-- 數(shù)據(jù)庫連接池:c3p0 --> <dependency> <groupId>com.mchange</groupId> <artifactId>c3p0</artifactId> <version>0.9.5.5</version> </dependency> <!--Servlet--> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> </dependency> <!--JSP--> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.2</version> </dependency> <!--jstl--> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!--Mybatis--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.5</version> </dependency> <!--Mybatis-Spring--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>2.0.5</version> </dependency> <!--Spring--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.2.8.RELEASE</version> </dependency> <!--Spring操作數(shù)據(jù)庫,還需要spring-jdbc--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdb c</artifactId> <version>5.2.6.RELEASE</version> </dependency> <!--lombok--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.12</version> </dependency> </dependencies>
最后為了防止maven配置文件無法被導(dǎo)出或生效
,加入以下代碼
<build> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> </resources> </build>
3、建立項目基本結(jié)構(gòu)
在
src/main/java
目錄下新建以下四個包,為后續(xù)實驗準(zhǔn)備
pojo
:用來放實體類dao
:數(shù)據(jù)訪問層,data access objectservice
:服務(wù)層,調(diào)用dao層controller
:控制層,調(diào)用service層
三、MyBatis層編寫
1、編寫數(shù)據(jù)庫配置文件
在resource目錄下新建database.properties
注意MySQL8.0以上要設(shè)置時區(qū),最后加上serverTimezone=Asia/Shanghai
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?useSSL=true&useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai jdbc.username=root jdbc.password=200024
2、IDEA關(guān)聯(lián)數(shù)據(jù)庫
時區(qū)問題解決方案:http://www.dbjr.com.cn/article/186512.htm
set global time_zone = '+8:00';
打開上述新建的數(shù)據(jù)表
3、編寫MyBatis核心配置文件
在resource目錄下新建mybatis-config.xml
數(shù)據(jù)源的配置,交給后續(xù)Spring
去做
<?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> <!--別名--> <typeAliases> <package name="pojo"/> </typeAliases> </configuration>
4、編寫pojo實體類
在pojo
包下創(chuàng)建數(shù)據(jù)庫表所對應(yīng)的實體類Books
,這里使用了lombok插件
@Data @AllArgsConstructor @NoArgsConstructor public class Books { private int bookID; private String bookName; private int bookCounts; private String detail; }
5、編寫dao層
1. 編寫Mapper接口
在dao
包下新建BookMapper
接口,編寫增刪改查四種業(yè)務(wù)對應(yīng)的方法
public interface BookMapper { //增加一本書 int addBook(Books books); //刪除一本書 //@Param注解指定傳入?yún)?shù)的名稱 int deleteBookByID(@Param("bookID") int id); //更新一本書 int updateBook(Books books); //查詢一本書 //@Param注解指定傳入?yún)?shù)的名稱 Books queryByID(@Param("bookID") int id); //查詢?nèi)康臅? List<Books> queryAllBooks(); }
2. 編寫Mapper接口對應(yīng)的Mapper.xml
一個Mapper.xml
對應(yīng)一個Mapper接口
,要用namespace
綁定上述接口
實現(xiàn)上述接口里的所有方法
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="dao.BookMapper"> <!--增加一本書--> <insert id="addBook" parameterType="pojo.Books"> insert into ssmbuild.books(bookName,bookCount,detail) values (#{bookName},#{bookCount},#{detail}) </insert> <!--刪除一本書--> <delete id="deleteBookByID" parameterType="int"> delete from ssmbuild.books where bookID=#{bookID} </delete> <!--更新一本書--> <update id="updateBook" parameterType="pojo.Books"> update ssmbuild.books set bookName=#{bookName},bookCounts=#{bookCounts},detail=#{detail} where bookID=#{bookID} ; </update> <!--查詢一本書--> <select id="queryByID" resultType="pojo.Books"> select * from ssmbuild.books where bookID=#{bookID} </select> <!--查詢所有書--> <select id="queryAllBooks" resultType="pojo.Books"> select * from ssmbuild.books </select> </mapper>
然后到mybatis核心配置文件
中注冊上述mapper.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> <!--別名--> <typeAliases> <package name="pojo"/> </typeAliases> <!--注冊mapper--> <mappers> <mapper class="dao.BookMapper"/> </mappers> </configuration>
6、編寫service層
1. 編寫service層的接口
在service
包下新建BookService
接口,同Mapper接口
里的方法一致
package service; import pojo.Books; import java.util.List; public interface BookService { //增加一本書 int addBook(Books books); //刪除一本書 int deleteBookByID(int id); //更新一本書 int updateBook(Books books); //查詢一本書 Books queryByID(int id); //查詢?nèi)康臅? List<Books> queryAllBooks(); }
2. 編寫service層接口實現(xiàn)類
然后再service
包下新建上述接口的實現(xiàn)類BookServiceImpl
service層
用來調(diào)用dao層
,所以內(nèi)置私有屬性為dao層的Mapper接口對象
package service; import pojo.Books; import java.util.List; public interface BookService { //增加一本書 int addBook(Books books); //刪除一本書 int deleteBookByID(int id); //更新一本書 int updateBook(Books books); //查詢一本書 Books queryByID(int id); //查詢?nèi)康臅? List<Books> queryAllBooks(); }
四、Spring層編寫
1、Spring整合dao層
在resource目錄下新建spring-dao.xml
關(guān)聯(lián)數(shù)據(jù)庫配置文件database.properties
,要引入context約束
配置MyBatis
數(shù)據(jù)源,這里使用第三方的c3p0
,還可以附加一些私有屬性
創(chuàng)建sqlSessionFactory
,在 MyBatis-Spring 中,則使用 SqlSessionFactoryBean
來創(chuàng)建,要配置兩個重要屬性
configLocation
綁定MyBatis核心配置文件dataSource
指定數(shù)據(jù)源(必要)
配置自動掃描包dao
,動態(tài)實現(xiàn)了dao層接口可以注入到Spring容器中
(在原來我們是創(chuàng)建sqlSessionTemplate
對象,然后再創(chuàng)建一個Mapper接口實現(xiàn)類,其中內(nèi)置sqlSessionTemplate
私有對象,通過該對象進(jìn)行操作)
<?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.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"> <!--1.關(guān)聯(lián)數(shù)據(jù)庫配置文件--> <context:property-placeholder location="classpath:database.properties"/> <!--2.數(shù)據(jù)庫連接池 dbcp 半自動化操作 不能自動連接 c3p0 自動化操作(自動的加載配置文件 并且設(shè)置到對象里面) druid、hikari--> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <!--配置連接池屬性,使用了EL表達(dá)式--> <property name="driverClass" value="${jdbc.driver}"/> <property name="jdbcUrl" value="${jdbc.url}"/> <property name="user" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> <!-- c3p0連接池的私有屬性 --> <property name="maxPoolSize" value="30"/> <property name="minPoolSize" value="10"/> <!-- 關(guān)閉連接后不自動commit --> <property name="autoCommitOnClose" value="false"/> <!-- 獲取連接超時時間 --> <property name="checkoutTimeout" value="10000"/> <!-- 當(dāng)獲取連接失敗重試次數(shù) --> <property name="acquireRetryAttempts" value="2"/> </bean> <!--3.sqlSessionFactory--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!--引用上述數(shù)據(jù)源--> <property name="dataSource" ref="dataSource"/> <!--綁定MyBatis配置文件--> <property name="configLocation" value="classpath:mybatis-config.xml"/> </bean> <!--4.配置dao接口掃描包,動態(tài)實現(xiàn)了Dao接口可以注入到Spring容器中--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!--注入sqlSessionFactory--> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> <!--要掃描的dao包--> <property name="basePackage" value="dao"/> </bean> </beans>
2、Spring整合service層
在resource目錄下新建spring-service.xml
配置掃描service包
,使該包下的注解生效
將所有業(yè)務(wù)類注入到Spring
中
配置聲明式事務(wù),需要注入數(shù)據(jù)源
<?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.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"> <!--1.掃描service下的包,這個包下的注解就會生效--> <context:component-scan base-package="service"/> <!--將所有的業(yè)務(wù)類注入到Spring,可以通過配置或者注解實現(xiàn)--> <bean id="BookServiceImpl" class="service.BookServiceImpl"> <!--這里的ref指向spring-dao.xml最后Spring注入的dao接口--> <property name="bookMapper" ref="bookMapper"/> </bean> <!--聲明式事務(wù)配置--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!--注入數(shù)據(jù)源--> <property name="dataSource" ref="dataSource"/> </bean> </beans>
五、SpringMVC層編寫
1、編寫spring-mvc.xml
自動掃描包
過濾靜態(tài)資源
支持mvc注解驅(qū)動
視圖解析器
<?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" xmlns:context="http://www.springframework.org/schema/context" 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 http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"> <!--開啟SpringMVC注解驅(qū)動--> <mvc:annotation-driven/> <!--靜態(tài)資源過濾--> <mvc:default-servlet-handler/> <!--掃描包controller--> <context:component-scan base-package="controller"/> <!--視圖解析器--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> </bean> </beans>
2、Spring配置文件整合
applicationContext.xml
導(dǎo)入上述配置文件,作為整體的配置文件
<?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"> <import resource="spring-dao.xml"/> <import resource="spring-service.xml"/> <import resource="spring-mvc.xml"/> </beans>
3、配置web.xml
- 注冊
DispatcherServlet
,需要綁定SpringMVC配置文件,這里一定要綁定整體的配置文件applicationContext.xml
,并設(shè)置啟動級別 - 增加亂碼過濾
- 設(shè)置session過期時間
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <!--DispatcherServlet--> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!--亂碼過濾--> <filter> <filter-name>encodingFilter</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>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!--session過期時間--> <session-config> <session-timeout>15</session-timeout> </session-config> </web-app>
4、編寫Controller
再controller包
下新建BookController
類
@Controller @RequestMapping("/book") public class BookController { //controller層調(diào)用service層 @Autowired @Qualifier("BookServiceImpl") private BookService bookService; //查詢?nèi)繒?,并且返回到一個頁面進(jìn)行顯示 @RequestMapping("/allBooks") public String list(Model model) { List<Books> books = bookService.queryAllBooks(); model.addAttribute("list", books); return "allBooks"; } }
5、編寫視圖層
在web/WEB-INF/
目錄下新建jsp
包,用來存放我們自定義視圖頁面
1. 編寫index.jsp
超鏈接跳轉(zhuǎn)到我們自定的展示所有書籍頁面allBooks.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>首頁</title> </head> <body> <h5> <a href="${pageContext.request.contextPath}/book/allBooks">進(jìn)入書籍頁面</a> </h5> </body> </html>
2. 編寫展示所有書籍頁面allBooks.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>全部書籍展示</title> </head> <body> <h1>全部書籍展示</h1> ${list} </body> </html>
6、運(yùn)行測試
配置Tomcat啟動測試,記得添加lib目錄,否則Tomcat啟動不來
啟動Tomcat后,默認(rèn)進(jìn)入的index.jsp
然后我們點擊超鏈接
成功顯示了我們的所有書籍!
到此位置,SSM整合項目到此結(jié)束,后續(xù)大家可以自己實現(xiàn)相關(guān)業(yè)務(wù)!??!
到此這篇關(guān)于2020最新版SSM框架整合教程的文章就介紹到這了,更多相關(guān)SSM框架整合內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Spring?Boot?利用?XML?方式整合?MyBatis
這篇文章主要介紹了Spring?Boot?利用?XML?方式整合?MyBatis,文章圍繞主題的相關(guān)資料展開詳細(xì)的內(nèi)容介紹,具有一定的參考價值,組要的小伙伴可以參考一下2022-05-05Spring Cloud Alibaba Nacos Config配置中心實現(xiàn)
這篇文章主要介紹了Spring Cloud Alibaba Nacos Config配置中心實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-04-04Java基本數(shù)據(jù)類型和運(yùn)算符詳解
這篇文章主要介紹了Java基本數(shù)據(jù)類型和運(yùn)算符,結(jié)合實例形式詳細(xì)分析了java基本數(shù)據(jù)類型、數(shù)據(jù)類型轉(zhuǎn)換、算術(shù)運(yùn)算符、邏輯運(yùn)算符等相關(guān)原理與操作技巧,需要的朋友可以參考下2020-02-02@CacheEvict中的allEntries與beforeInvocation的區(qū)別說明
這篇文章主要介紹了@CacheEvict中的allEntries與beforeInvocation的區(qū)別說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-12-12