SSM整合
环境搭建
1. 建表
CREATE DATABASE `ssmbuild`;
USE `ssmbuild`;
DROP TABLE IF EXISTS `books`;
CREATE TABLE `book` (
`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,'从进门到进牢');
2. 导包
<dependencies>
<!--Junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</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.10</version>
</dependency>
</dependencies>
3. 设置Maven资源过滤
- pom.xml
<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. 创建项目结构和配置框架
- 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">
-
applicationContext.xml
<?xml version=”1.0” encoding=”UTF-8”?>
-
db.properties
<a name="Mybatis"></a>
## Mybatis
<a name="8b3dcf3d"></a>
### 1. 创建实体类
```java
package com.william.po;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Book {
private int bookID;
private String bookName;
private int bookCounts;
private String detail;
}
2. 创建Dao层Mapper接口和Mapper.xml文件
- Mapper.class
package com.william.dao;
import com.william.po.Book;
import java.util.List;
public interface BookMapper {
//增加一个Book
int addBook(Book book);
//根据id删除一个Book
int deleteBookById(int id);
//更新Book
int updateBook(Book book);
//根据id查询,返回一个Book
Book queryBookById(int id);
//查询全部Book,返回list集合
List<Book> queryAllBook();
}
Mapper.xml
<?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.william.dao.BookMapper">
<!--增加一个Book-->
<insert id="addBook" parameterType="Book">
insert into ssmbuild.book(bookName,bookCounts,detail)
values (#{bookName}, #{bookCounts}, #{detail})
</insert>
<!--根据id删除一个Book-->
<delete id="deleteBookById" parameterType="int">
delete from ssmbuild.book where bookID=#{bookID}
</delete>
<!--更新Book-->
<update id="updateBook" parameterType="Book">
update ssmbuild.book
set bookName = #{bookName},bookCounts = #{bookCounts},detail = #{detail}
where bookID = #{bookID}
</update>
<!--根据id查询,返回一个Book-->
<select id="queryBookById" resultType="Book">
select * from ssmbuild.book
where bookID = #{bookID}
</select>
<!--查询全部Book-->
<select id="queryAllBook" resultType="Book">
SELECT * from ssmbuild.book
</select>
</mapper>
3. 创建Service层的接口和实现类,并在其中调用Dao层
- Service.class ```java package com.william.service;
import com.william.po.Book; import java.util.List;
public interface BookService {
//增加一个Book
int addBook(Book book);
//根据id删除一个Book
int deleteBookById(int id);
//更新Book
int updateBook(Book book);
//根据id查询,返回一个Book
Book queryBookById(int id);
//查询全部Book,返回list集合
List
-
ServiceImpl.class
```java
package com.william.service;
import com.william.dao.BookMapper;
import com.william.po.Book;
import java.util.List;
public class BookServiceImpl implements BookService {
// 持有Dao层
public BookMapper bookMapper;
// 方法均调用Dao层中同名方法
@Override
public int addBook(Book book) {
return bookMapper.addBook(book);
}
@Override
public int deleteBookById(int id) {
return bookMapper.deleteBookById(id);
}
@Override
public int updateBook(Book book) {
return bookMapper.updateBook(book);
}
@Override
public Book queryBookById(int id) {
return bookMapper.queryBookById(id);
}
@Override
public List<Book> queryAllBook() {
return bookMapper.queryAllBook();
}
public void setBookMapper(BookMapper bookMapper) {
this.bookMapper = bookMapper;
}
}
Spring
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">
<!-- 1.关联数据库配置文件-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- 2.数据库连接池 -->
<!--数据库连接池
dbcp 半自动化操作 不能自动连接
c3p0 自动化操作(自动的加载配置文件 并且设置到对象里面)
-->
<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}"/>
<!-- c3p0连接池的私有属性 -->
<property name="maxPoolSize" value="30"/>
<property name="minPoolSize" value="10"/>
<!-- 关闭连接后不自动commit -->
<property name="autoCommitOnClose" value="false"/>
<!-- 获取连接超时时间 -->
<property name="checkoutTimeout" value="10000"/>
<!-- 当获取连接失败重试次数 -->
<property name="acquireRetryAttempts" value="2"/>
</bean>
<!-- 3.配置SqlSessionFactory对象 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 注入数据库连接池 -->
<property name="dataSource" ref="dataSource"/>
<!-- 配置MyBatis全局配置文件: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.william.dao"/>
</bean>
</beans>
重点!!!!
参考:https://blog.csdn.net/qq598535550/article/details/51703190?ops_request_misc=%7B%22request%5Fid%22%3A%22160359229319724842930227%22%2C%22scm%22%3A%2220140713.130102334..%22%7D&request_id=160359229319724842930227&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2top_click~default-4-51703190.pc_first_rank_v2_rank_v28&utm_term=ssm&spm=1018.2118.3001.4187
spring-service.xml ```xml <?xml version=”1.0” encoding=”UTF-8”?>
<a name="SpringMVC"></a>
## SpringMVC
-
web.xml
```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>
spring-mvc.xml ```xml <?xml version=”1.0” encoding=”UTF-8”?>
<a name="dc53819c"></a>
## 配置文件的整合
<a name="bbce0330"></a>
### 1.使用IDEA
![](https://gitee.com/qinweilong/cloudimage/raw/master/img/image-20201025154842299.png#alt=image-20201025154842299)
<a name="3e2ce77f"></a>
### 2.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"
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层
- bookController.class ```java package com.william.controller;
import com.william.po.Book; import com.william.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.PathVariable; 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<Book> list = bookService.queryAllBook();
model.addAttribute("list", list);
return "allBook";
}
// 增加
@RequestMapping("/toAddBook")
public String toAddPaper() {
return "addBook";
}
@RequestMapping("/addBook")
public String addPaper(Book book) {
System.out.println(book);
bookService.addBook(book);
// 重定向
return "redirect:/book/allBook";
}
// 修改
@RequestMapping("/toUpdateBook")
public String toUpdateBook(Model model, int id) {
Book book = bookService.queryBookById(id);
System.out.println(book);
model.addAttribute("book", book);
return "updateBook";
}
@RequestMapping("/updateBook")
public String updateBook(Model model, Book book) {
System.out.println(book);
bookService.updateBook(book);
Book books = bookService.queryBookById(book.getBookID());
model.addAttribute("books", book);
return "redirect:/book/allBook";
}
// 删除
@RequestMapping("/del/{bookId}")
public String deleteBook(@PathVariable("bookId") int id) {
bookService.deleteBookById(id);
return "redirect:/book/allBook";
}
} ```
另外编写对应前端页面
- allBook.jsp
- addBook.jsp
- updateBook.jsp