一、环境
IDEA
Mysql 5.7.19
tomcat 8
maven 3.8.4
二、数据库设计
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,'从进门到进牢');
三、新建一个maven项目
- 将这个项目提升为web项目
- 连接mysql
- 配置上tomcat
![](https://i-blog.csdnimg.cn/blog_migrate/aa5ea28878cd26a9cf9bc86d488cffe9.png)
-
四、pom.xml导入依赖
-
Junit测试
-
mybatis依赖,mybatis连接spring依赖
-
spring依赖
-
servlet,jsp
-
数据库连接池,JDBC
别忘了设置静态资源过滤
<?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>org.example</groupId>
<artifactId>ssm</artifactId>
<version>1.0-SNAPSHOT</version>
<!--1. 添加依赖-->
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!--版本要和mysql的版本匹配起来,mysql是5开头的话这个也要以5开头,如果是8开头。。。-->
<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>
<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>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.13</version>
</dependency>
<!-- 版本和mybatis,spring的版本有关 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.2</version>
</dependency>
<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.18.26</version>
<scope>provided</scope>
</dependency>
</dependencies>
<!--2、静态资源过滤-->
<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>
</project>
-
五、项目结构
![](https://i-blog.csdnimg.cn/blog_migrate/dd89c4a445e5d6912c6ef80605fbf95a.png)
所有的配置文件:
配置文件之间的关联关系:
六、整合mybatis层
6.1 配置文件
(1)mybatis核心配置文件
mybatis核心配置文件只干两件事:
-
起别名
-
注册mapper.xml文件
db.properties的引入交给spring去干
<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--1、别名-->
<typeAliases>
<package name=""/>
</typeAliases>
<!--2、注册mapper.xml -->
<mappers>
</mappers>
</configuration>
(2)db.properties
如果用的mysql是8版本及以上,url参数里还要加上上海的时区
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/db_mybatis?useSSL=false
username=root
password=123456
6.2 pojo
注意,参数名最好和数据库字段名保持一致
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Books {
private int bookID;
private String bookName;
private String bookCounts;
private String detail;
}
6.3 dao
BooksMapper.java
public interface BooksMapper {
//增加一本书
int addBook(Books books);
//删除一本书
int deleteBookById(@Param("bookID") int id);
//更新一本书
int updateBook(Books books);
//查询一本书
Books queryBookById(@Param("bookID") int id);
//查询全部的书
List<Books> queryAllBook();
}
BooksMapper.xml
<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="dao.BooksMapper">
<insert id="addBook" parameterType="pojo.Books">
insert into ssmbuild.books(bookName,bookCounts,detail)
values (#{bookName},#{bookCounts},#{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="queryBookById" resultType="pojo.Books">
select * from ssmbuild.books
where bookID=#{bookID}
</select>
<select id="queryAllBook" resultType="pojo.Books">
select * from ssmbuild.books
</select>
</mapper>
然后立马把这个mapper.xml文件注册到mybatis-config.xml里面去。
6.4 service
BookService.java
public interface BookService {
//增加一本书
int addBook(Books books);
//删除一本书
int deleteBookById(int id);
//更新一本书
int updateBook(Books books);
//查询一本书
Books queryBookById(int id);
//查询全部的书
List<Books> queryAllBook();
}
BookServiceImpl.java
public class BookServiceImpl implements BookService{
//service层组合dao层
private BooksMapper booksMapper;
public void setBooksMapper(BooksMapper booksMapper){
this.booksMapper = booksMapper;
}
//-----------------------
public int addBook(Books books) {
return booksMapper.addBook(books);
}
public int deleteBookById(int id) {
return booksMapper.deleteBookById(id);
}
public int updateBook(Books books) {
return booksMapper.updateBook(books);
}
public Books queryBookById(int id) {
return booksMapper.queryBookById(id);
}
public List<Books> queryAllBook() {
return booksMapper.queryAllBook();
}
}
七、整合spring层
7.1 spring整合dao层
新建spring-dao.xml
- 关联数据库配置文件db.properties
- 配置第三方连接池(可以用spring自带的,但是这里我们用第三方的C3P0)
- sqlSession
- 【可选】配置dao接口扫描包,动态实现dao接口注入spring容器中。如果实现了这个配置,就不用写下面的带@Repository注解的 BookMapperImpl extends sqlSessionDaoSupport implements BookMapper
<?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
https://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:db.properties"/>
<!--2、配置连接池-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${driver}"/>
<property name="jdbcUrl" value="${url}"/>
<property name="user" value="${username}"/>
<property name="password" value="${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、sqlSession实例,在这里把spring和mybatis配置文件联系起来-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--注入连接池(datasource-->
<property name="dataSource" ref="dataSource"/>
<!--绑定mybatis的配置文件-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
<!--4、配置dao接口扫描包,动态实现dao接口注入到spring容器中(这样就不用写BooksMapperImpl.java文件了,也就是从此以后不用写标有@Repository的类了-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--注入sqlSessionFactory--> <!--为什么这里不用ref而用value?-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!--要扫描的包-->
<property name="basePackage" value="dao"/>
</bean>
</beans>
7.2 spring整合service层
新建spring-service.xml
- 扫描service层,开启注解支持
- 将service层实现类BookServiceImpl注入到spring中
- 将mybatis提供的事务管理器注入到spring中(PS:注入到spring中表明创建一个实例,以后在项目中就能用事务管理器了)
<?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
https://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"/>
<!--2. 将我们的所有业务类,注入到spring,可以通过配置或者注解@Service+@Autowired实现,然后上面的扫描包就会把带有@Service注解的类注入到spring中(一般我们都用注解的形式,这里只是回顾一下<bean> 注入的形式)-->
<bean id="BookServiceImpl" class="service.BookServiceImpl">
<property name="booksMapper" ref="booksMapper"/>
</bean>
<!--3、声明式事务配置-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--注入连接池/数据源-->
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>
记得点右上角,把所有xml文件关联起来,不然会出现下面的爆红。
然后我们把spring-dao.xml,spring-service.xml以及待会创建的spring-mvc.xml都import进applicationContext.xml里。
PS:如果我们不用<bean>去注入BooksServiceImpl的bean的话,还可以用@Servive+@Autowired+@qualifier("booksMapper")注解去代替。
这里注意,因为我们在spring-dao.xml中用了MapperScannerConfigurer的配置而不用写booksMapper的实现类BooksMapperImpl了,@Qualifier里的参数本来应该是"booksMapperImpl",但是现在因为这个实现类是运行时自动生成的,我们没法写booksMapperImpl,写接口小写就行"booksMapper".
八、整合springMVC层
- 首先将这个项目提升为web项目,会自动增加web.xml配置文件
- web.xml里的“死配置”
- 注入DisPatcherServlet
- 乱码过滤
- 设置一个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">
<!--1.注册DispatcherServlet-->
<servlet>
<servlet-name>SpringMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--关联SpringMVC配置文件:通过初始化参数指定SpringMVC配置文件的位置-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</init-param>
<!--配置DispatcherServlet启动级别:数字越小,启动越早-->
<load-on-startup>1</load-on-startup>
</servlet>
<!--所有请求都会被springmvc拦截-->
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<url-pattern>/</url-pattern> <!--但jsp页面除外,/*才包括jsp页面-->
</servlet-mapping>
<!--2、乱码过滤-->
<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>
<!--3、session时效的时间-->
<session-config>
<session-timeout>15</session-timeout>
</session-config>
</web-app>
注意:为什么这么写我没弄明白
- 新建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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--1、注解驱动,会自动注册RequestMappingHandlerMapping与RequestMappingHandlerAdapter两个Bean-->
<mvc:annotation-driven/>
<!--2、静态资源过滤-->
<mvc:default-servlet-handler/>
<!--3、扫描包-->
<context:component-scan base-package="controller"/>
<!--4、视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
九、测试——查询全部书籍
9.1 编写controller
新增controller/BooksController.java类
@Controller
@RequestMapping("/books")
public class BooksController {
@Autowired
@Qualifier("bookServiceImpl")
private BookServiceImpl bookServiceImpl;
@RequestMapping("/allBook")
public String queryAllBooks(Model model){
List<Books> booksList = bookServiceImpl.queryAllBook();
model.addAttribute(booksList);
return "showBooks";
}
}
新增WEB-INF/jsp/showBooks.jsp页面,但是我们不展示查询结果,只是有这个页面,如果跳转过来说明测试成功。
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h4>展示booksLists</h4>
</body>
</html>
在index.jsp的<body>标签里加点击跳转
<h3>
<a href="${pageContext.request.contextPath}/books/allBook">进入书籍页面</a>
</h3>
9.2 给项目增加lib目录
只要是springMVC项目就给artifacts增加lib目录,不然会出现404资源找不到的问题。
9.3 运行tomcat
点击主页的“进入书籍页面”,本应该跳转到showBooks.jsp,但是出现mysql登录失败问题:
折腾了一顿,终于想通是什么问题了!我明明在db.properties里写的数据库用户为root,但是它却用DELL给我登录的?突然想到可能是我在db.properties定义的变量和环境变量重名了!去环境变量看,果然系统变量里也有一个username变量。
解决方法就是把自己定义的变量全都加上前缀
再次运行,跳转成功!
然后再美化一下showBooks.jsp这个前端页面
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>书籍展示</title>
<%--引入bootstrap美化界面--%>
<link href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="row clearfix">
<div class="col-md-12 column">
<div class="page-header">
<h2>
<small>书籍列表——显示所有书籍</small>
</h2>
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-md-12 column">
<table class="table table-hover table-striped">
<thead>
<tr>
<th>书籍编号</th>
<th>书籍名称</th>
<th>书籍数量</th>
<th>书籍详情</th>
</tr>
</thead>
<%--遍历list--%>
<tbody>
<c:forEach var="book" items="${booksList}">
<tr>
<td>${book.bookID}</td>
<td>${book.bookName}</td>
<td>${book.bookCounts}</td>
<td>${book.detail}</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
效果如下:
十、添加一本书
思路:我们要在showBooks.jsp页面新增一个“添加书籍”的按钮,点击这个按钮就能跳转到新增书籍页面addBook.jsp。所以我们要在showBooks.jsp页面新增一个“添加书籍”的按钮,然后写一个跳转controller,返回值return "showBooks.jsp",新增showBooks.jsp页面,里面可以填书籍信息,外加一个提交按钮。点了这个提交按钮以后,还应该跳转到一个把书籍保存到数据库的controller,所以再写一个把书籍保存到数据库的controller。
(1)在showBooks.jsp页面新增一个“添加书籍”的按钮
(2)新增跳转controller ,url定义为“/toAddBook”
@RequestMapping("/toAddBook")
public String toAddBook(){
return "addBook";
}
(3)新增添加书籍页面addBook.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>添加书籍</title>
<%--引入bootstrap美化界面--%>
<link href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<%--标题--%>
<div class="row clearfix">
<div class="col-md-12 column">
<div class="page-header">
<h2>
<small>添加书籍</small>
</h2>
</div>
</div>
</div>
<%--提交表单--%>
<form action="${pageContext.request.contextPath}/books/addBook" method="post">
<div class="form-group">
<label>书籍名称:</label>
<input type="text" name="bookName" class="form-control"> <%--name必须要和Books类的字段值一样,不然提交以后对应不上去--%>
</div>
<div class="form-group">
<label>书籍数量:</label>
<input type="text" name="bookCounts" class="form-control">
</div>
<div class="form-group">
<label>书籍描述:</label>
<input type="text" name="detail" class="form-control">
</div>
<%--提交按钮--%>
<div class="form-group">
<input type="submit" class="form-control" value="添加">
</div>
</form>
</div>
</body>
</html>
有个问题,当我们在这个页面只给出了书籍名,其他信息空着,提交后会报错。解决方法:
给每个字段后面加required属性。如果在前端没填完整,会一直提醒你填完整,不给你提交!
(4)新增添加书籍的controller接口
@RequestMapping("/addBook")
public String addBook(Books books){
bookServiceImpl.addBook(books);
return "redirect:/books/allBook"; //重定向到展示页面
}
测试成功!