SSM框架整合
环境:
IDEA
MySQL 5.7.19
Tomcat 9
Maven 3.6
最近刚跟着狂神学完SSM框架,自己多练习整合几遍,写一篇整合文档,方便自己以后使用。
数据库环境
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 '数量',
`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,'从进门到进牢');
基本环境搭建
1、新建一Maven项目!ssmbuildTest2 , 添加web的支持
2、导入相关的pom依赖!
<!-- 相关依赖junit 数据库驱动 数据库连接池 Servlet jsp Mybatis Spring-->
<dependencies>
<!-- junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- 数据库驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!-- 数据库连接池-->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<!-- Servlet jsp-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
</dependency>
<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.2</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.2</version>
</dependency>
<!-- spring-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.4</version>
</dependency>
</dependencies>
3.资源过滤配置
在我们使用Maven构建项目的时候,会默认过滤掉静态资源,所以,需要手动来配置
-
静态资源,包含HTMl,图片,CSS,JS等不需要与数据库交互的一类文件
-
动态资源:需要与数据库交互,可以根据需要显示不同的数据,不需要修改页面
<!-- maven资源过滤配置-->
<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>
4、建立基本结构和配置框架!
-
com.ding.pojo
-
com.ding.dao
-
com.ding.service
-
com.ding.controller
mybatis-config.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>
</configuration>
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">
</beans>
Mybatis层编写
1、数据库配置文件 database.properties
jdbc.driver=com.mysql.jdbc.Driver
# 如果使用的是MySQL8.0+ 增加一个时区的配置; &serverTimezone=Asia/Shanghai
jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?useSSL=true&useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai
jdbc.username=root
jdbc.password=123456
2、IDEA关联数据库
连接后
3、编写MyBatis的核心配置文件
<?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="com.ding.pojo"/>
</typeAliases>
<!-- 这里我是先写好后写的文章,参考的话可以先删除,后面再写-->
<mappers>
<mapper class="com.ding.dao.BookMapper"></mapper>
</mappers>
</configuration>
4、编写数据库对应的实体类 com.ding.pojo.Books
使用lombok插件!不能用的注意导入依赖
package com.ding.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Books {
private int bookID;
private String bookName;
private int bookCounts;
private String detail;
}
5、编写Dao层的 Mapper接口!
package com.ding.dao;
import com.ding.pojo.Books;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface BookMapper {
// 增加一本书
int addBook(Books book);
// 根据id 删除一本书
int deleteBook(@Param("bookID") int id);
// 更新一本书
int updateBook(Books book);
// 根据id 查询一本书
Books selectBookByID(int id);
// 查询全部图书
List<Books> queryAllBooks();
}
6、编写接口对应的 Mapper.xml 文件。需要导入MyBatis的包;
<?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="com.ding.dao.BookMapper">
<!-- 增加一本书-->
<insert id="addBook" parameterType="Books">
insert into ssmbuild.books (bookID, bookName, bookCounts, detail)
values (#{bookID}, #{bookName}, #{bookCounts}, #{detail})
</insert>
<!-- 根据id 删除一本书-->
<delete id="deleteBook" parameterType="int">
delete
from ssmbuild.books
where bookID = #{bookID}
</delete>
<!-- 更新一本书-->
<update id="updateBook" parameterType="Books">
update ssmbuild.books
set bookName=#{bookName},
bookCounts=#{bookCounts},
detail=#{detail}
where bookID = #{bookID}
</update>
<select id="selectBookByID" resultType="Books">
select *
from ssmbuild.books
where bookID = #{bookID}
</select>
<select id="queryAllBooks" resultType="Books">
select *
from ssmbuild.books
</select>
</mapper>
7、编写Service层的接口和实现类
接口:
package com.ding.service;
import com.ding.pojo.Books;
import org.apache.ibatis.annotations.Param;
import java.util.List;
//需要实现调用dao
public interface BookService {
// 增加一本书
int addBook(Books book);
// 根据id 删除一本书
int deleteBook(@Param("bookID") int id);
// 更新一本书
int updateBook(Books book);
// 根据id 查询一本书
Books selectBookByID(int id);
// 查询全部图书
List<Books> queryAllBooks();
}
实现类:
package com.ding.service;
import com.ding.dao.BookMapper;
import com.ding.pojo.Books;
import java.util.List;
public class BookServiceImpl implements BookService {
private BookMapper bookMapper;
public void setBookMapper(BookMapper bookMapper) {
this.bookMapper = bookMapper;
}
@Override
public int addBook(Books book) {
return bookMapper.addBook(book);
}
@Override
public int deleteBook(int id) {
return bookMapper.deleteBook(id);
}
@Override
public int updateBook(Books book) {
return bookMapper.updateBook(book);
}
@Override
public Books selectBookByID(int id) {
return bookMapper.selectBookByID(id);
}
@Override
public List<Books> queryAllBooks() {
return bookMapper.queryAllBooks();
}
}
OK,到此,底层需求操作编写完毕!
Spring层
1、配置Spring整合MyBatis,我们这里数据源使用c3p0连接池;
2、我们去编写Spring整合Mybatis的相关的配置文件;spring-dao.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.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!-- 配置mybatis-->
<!-- 关联数据库文件-->
<context:property-placeholder location="classpath:database.properties"/>
<!-- 数据库连接池-->
<!-- 2.连接池
c3p0:自动化操作(自动化加载配置文件,并且可以自动设置到对象中)
dbcp:半自动化,不能自动连接
druid:
hikari:
-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!-- 配置SqlSessionFactory对象-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 注入数据库连接池-->
<property name="dataSource" ref="dataSource"/>
<!-- 配置mybais全局配置文件:mybatis-config.xml-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
<!-- 4.配置扫描Dao接口包,动态实现Dao接口注入到spring容器中 -->
<!--解释 :https://www.cnblogs.com/jpfss/p/7799806.html-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 注入sqlSessionFactory -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!-- 给出需要扫描Dao接口包 -->
<property name="basePackage" value="com.ding.dao"/>
</bean>
</beans>
3、Spring整合service层 spring-service.xml
相关爆红,需要在applicationContext.xml 中引入相关整合.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.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!-- 扫描service下的包-->
<context:component-scan base-package="com.ding.service"/>
<!--BookServiceImpl注入到IOC容器中-->
<bean id="BookServiceImpl" class="com.ding.service.BookServiceImpl">
<property name="bookMapper" ref="bookMapper"/>
</bean>
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 注入数据库连接池 -->
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 4.0 aop支持-->
</beans>
Spring层搞定!再次理解一下,Spring就是一个大杂烩,一个容器!对吧!
SpringMVC层
1、web.xml
<?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>DispatcherServlet</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>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--encodingFilter-->
<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>
2、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: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.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 配置SpringMVC -->
<!-- 1.开启SpringMVC注解驱动 -->
<mvc:annotation-driven />
<!-- 2.静态资源默认servlet配置-->
<mvc:default-servlet-handler/>
<!-- 3.配置jsp 显示ViewResolver视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- 4.扫描web相关的bean -->
<context:component-scan base-package="com.ding.controller" />
</beans>
3、Spring配置整合文件,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">
<import resource="spring-dao.xml"/>
<import resource="spring-service.xml"/>
<import resource="spring-mvc.xml"/>
</beans>
配置文件,暂时结束!
Controller 和 视图层编写
1、BookController 类编写 , 方法一:查询全部书籍
package com.ding.controller;
import com.ding.pojo.Books;
import com.ding.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
@Controller
@RequestMapping("/book")
public class BookController {
@Autowired
@Qualifier("BookServiceImpl")
private BookService bookService;
@RequestMapping("/allBook")
public String list(Model model){
List<Books> books = bookService.queryAllBooks();
for (Books book : books) {
System.out.println(book);
}
model.addAttribute("books",books);
return "allBook";
}
}
2、编写首页 index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<h3><a href="${pageContext.request.contextPath}/book/allBook">进入书籍页面</a></h3>
</body>
</html>
3、书籍列表页面 allbook.jsp 从简显示数据就行 注意创建位置,注意视图解析前缀后缀的解析就知道在哪创建了
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
${books}
</body>
</html>
基本书写完毕 接下来
配置tomcat测试
1.启动
配置有错误,在这里创建lib文件夹,导入jar包
再次启动: