目录
1.环境搭建
数据库环境
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,'从进门到进牢');
idea环境
- 1.新建一个maven项目 ssmbuild
- 2.导入pom.xml依赖
<!--依赖:junit、数据库驱动、连接池、servlet、jsp、mybatis、mybatis-spring、spring、lombok-->
<dependencies>
<!--junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
</dependency>
<!--mysql 驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.49</version>
</dependency>
<!--c3p0-->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.5</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.11</version>
</dependency>
<!--mybatis-spring-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.7</version>
</dependency>
<!--springmvc-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.23</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.23</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
</dependency>
</dependencies>
<!--在build中配置resources,来防止我们资源导出失败的问题-->
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
- 3.Maven资源过滤设置
<!--在build中配置resources,来防止我们资源导出失败的问题-->
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
- 4.idea连接数据库
- 5.建表
- 6.mybaits的配置文件
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>
-
7.Spring的配置文件
spring-mvc.xml、spring-service.xml、spring-dao.xml、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>
2.Mybatis层
-
1.数据库配置文件 :jdbc.properties
这里我还加了Druid连接池的配置
c3p0.driver=com.mysql.jdbc.Driver
c3p0.url=jdbc:mysql:///ssmbuild?useUnicode=true&characterEncoding=utf8&useSSL=false
c3p0.username=root
c3p0.password=000000
# 连接池中的最小空闲连接数
c3p0.minPoolSize=1
# 最大连接数
c3p0.maxPoolSize=10
# 最大等待时间(毫秒)
c3p0.checkoutTimeout=3000
# 当前获取连接失败重试次数
c3p0.acquireRetryAttempts=2
# 关闭连接后不自动commit
c3p0.autoCommitOnClose=false
- 2.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>
<!-- 专门用来做Mybatis配置文件的设置和别名-->
<!--<settings>-->
<!--</settings>-->
<typeAliases>
<!--可以给实体类的包下得文件起别名:类名首字母小写-->
<package name="shuangma.pojo" />
</typeAliases>
<!--配置数据源交给Spring去做-->
<!--绑定接口-->
<mappers>
<package name="shuangma.dao"/>
</mappers>
</configuration>
- 3.数据库实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Books {
//命名尽量和数据库一致,如果不一样需要去进行配置
private int bookID;
private String bookName;
private int bookCounts;
private String detail;
}
- 4.dao层mapper接口
public interface BookMapper {
//增加一本书
int addBook(Books book);
//根据id删除一本书
int deleteBookById(@Param("bookID") int bookID);
//根据id更新一本书
int updateBook(Books books);
//根据id查询一本书
Books queryBookById(@Param("bookID") int bookID);
//查询全部书
List<Books> queryAllBook();
//通过书名查询一本书
Books queryBookByName(@Param("bookName") String bookName);
}
- 5.dao层mapper对应的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="shuangma.dao.BookMapper">
<!--增加一本书-->
<insert id="addBook" parameterType="Books">
insert into books(bookName,bookCounts,detail)
values (#{bookName}, #{bookCounts}, #{detail})
</insert>
<!--根据id删除一本书-->
<delete id="deleteBookById" parameterType="int">
delete from books where bookID=#{bookID}
</delete>
<!--根据id更新一本书-->
<update id="updateBook" parameterType="Books">
update books
set bookName = #{bookName},bookCounts = #{bookCounts},detail = #{detail}
where bookID = #{bookID}
</update>
<!--根据id查询一本书-->
<select id="queryBookById" resultType="Books">
select * from books
where bookID = #{bookID}
</select>
<!--查询全部书-->
<select id="queryAllBook" resultType="shuangma.pojo.Books">
SELECT * from books
</select>
<!--通过书名查询一本书-->
<select id="queryBookByName" resultType="Books">
SELECT * from books where bookName=#{bookName}
</select>
</mapper>
- 6.service层接口
public interface BookService {
//增加一本书
int addBook(Books book);
//根据id删除一本书
int deleteBookById(int id);
//根据id更新一本书
int updateBook(Books books);
//根据id查询一本书
Books queryBookById(int id);
//查询全部书
List<Books> queryAllBook();
//通过书名查询一本书
Books queryBookByName(String bookName);
}
- 7.service层实现类
public class BookServiceImpl implements BookService{
//service(业务层) 调用dao层 组合dao
private BookMapper bookMapper;
public BookMapper getBookMapper() {
return bookMapper;
}
public void setBookMapper(BookMapper bookMapper) {
this.bookMapper = bookMapper;
}
@Override
public int addBook(Books book) {
return bookMapper.addBook(book);
}
@Override
public int deleteBookById(int id) {
return bookMapper.deleteBookById(id);
}
@Override
public int updateBook(Books books) {
return bookMapper.updateBook(books);
}
@Override
public Books queryBookById(int id) {
return bookMapper.queryBookById(id);
}
@Override
public List<Books> queryAllBook() {
return bookMapper.queryAllBook();
}
@Override
public Books queryBookByName(String bookName) {
return bookMapper.queryBookByName(bookName);
}
}
- 8.mybatis项目结构
3.Spring层
1.Spring整合Mybatis的相关的配置文件
spring-dao.xml
1.关联properties文件
<context:property-placeholder location="classpath:jdbc.properties"/>
2.连接c3p0数据源
如果需要更换其他数据源只需要导入依赖,修改class属性值跟property标签。
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${c3p0.driver}"/>
<property name="jdbcUrl" value="${c3p0.url}"/>
<property name="user" value="${c3p0.username}"/>
<property name="password" value="${c3p0.password}"/>
<!--最小连接池大小-->
<property name="minPoolSize" value="${c3p0.minPoolSize}"/>
<!--最大连接池大小-->
<property name="maxPoolSize" value="${c3p0.maxPoolSize}"/>
<!--最大等待时间(毫秒)-->
<property name="checkoutTimeout" value="${c3p0.checkoutTimeout}"/>
<!--当前获取连接失败重试次数-->
<property name="acquireRetryAttempts" value="${c3p0.acquireRetryAttempts}"/>
<!--关闭连接后不自动commit-->
<property name="autoCommitOnClose" value="${c3p0.autoCommitOnClose}"/>
</bean>
3.定义SqlSessionFactory
SqlSessionFactory需要注入数据源跟mybatis路径,这样mybatis-config.xml配置的内容才能生效
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!--关联mybatis配置文件 configLocation mybatis文件给定义一个名字-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
4.扫描映射器
- MapperScannerConfigurer会自动扫描指定包下的所有mapper接口,为我们生成mapper接口的实现类并注入到Spring容器中。
- 注入Spring容器中的的命名策略是使用映射器的非大写的非完全限定类名。可以通过注解@Repository("xx")来修改。
- MapperScannerConfigurer是需要使用sqlSessionFactory的,但是当只有一个的时候可以省略,如果要显示注入可以使用如下代码注入来注入,注意这里引用上面的sqlSessionFactory,但是是value的属性值,而不是ref。
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
- 这是省略了sqlSession的,如果没有省略sqlSession则sqlSessionFactoryBeanName需要改成sqlSessionTemplateBeanName,并通过value值引入定义的sqlSession。
<!--4.配置dao接口扫描包,动态的实现了Dao接口可以注入到Spring容器中-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--注入sqlSessionFactory 如果工厂只有一个sqlSessionFactory的bean此配置可以省略-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!--扫描要扫描的dao包,如果有多个包使用逗号或者分号分割-->
<property name="basePackage" value="shuangma.dao"/>
</bean>
5.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
http://www.springframework.org/schema/context/spring-context.xsd">
<!--专注于数据库的使用-->
<!--1.关联数据库配置文件-->
<context:property-placeholder location="classpath:c3p0.properties"/>
<!--2.Druid连接池-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${c3p0.driver}"/>
<property name="jdbcUrl" value="${c3p0.url}"/>
<property name="user" value="${c3p0.username}"/>
<property name="password" value="${c3p0.password}"/>
<!--最小连接池大小-->
<property name="minPoolSize" value="${c3p0.minPoolSize}"/>
<!--最大连接池大小-->
<property name="maxPoolSize" value="${c3p0.maxPoolSize}"/>
<!--最大等待时间(毫秒)-->
<property name="checkoutTimeout" value="${c3p0.checkoutTimeout}"/>
<!--当前获取连接失败重试次数-->
<property name="acquireRetryAttempts" value="${c3p0.acquireRetryAttempts}"/>
<!--关闭连接后不自动commit-->
<property name="autoCommitOnClose" value="${c3p0.autoCommitOnClose}"/>
</bean>
<!--3.sqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!--关联mybatis配置文件 configLocation mybatis文件给定义一个名字-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
<!--4.配置dao接口扫描包,动态的实现了Dao接口可以注入到Spring容器中-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--注入sqlSessionFactory 如果工厂只有一个sqlSessionFactory的bean此配置可以省略-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!--扫描要扫描的dao包,如果有多个包使用逗号或者分号分割-->
<property name="basePackage" value="shuangma.dao"/>
</bean>
</beans>
2.spring整合service层
spring-service.xml
1.自动扫描
<context:component-scan base-package="shuangma.service"/>
2.业务类注入spring容器
<bean id="BookServiceImpl" class="shuangma.service.BookServiceImpl">
<property name="bookMapper" ref="bookMapper"/>
</bean>
3.声明式事务
配置声明式事务,注入数据源,需要导入tx的命名空间。
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--注入数据源-->
<property name="dataSource" ref="dataSource"/>
</bean>
4.spring-service.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
http://www.springframework.org/schema/context/spring-context.xsd">
<!--1.扫描service下的包-->
<context:component-scan base-package="shuangma.service"/>
<!--2.将我们的所有业务类,注入到spring,可以通过配置或者注解实现-->
<bean id="BookServiceImpl" class="shuangma.service.BookServiceImpl">
<property name="bookMapper" ref="bookMapper"/>
</bean>
<!--3.声明式事务-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--注入数据源-->
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>
4.SpringMVC层
1.web层
添加web框架支持
在/WEB-INF目录下建一个jsp文件夹
web.xml
1.配置DispatcherServlet
<!--1.配置DispatcherServlet 这个是SpringMVC的核心:请求分发器(前端控制器)-->
<servlet>
<servlet-name>springMVC</servlet-name>
<!--这是spring自己写好的-->
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--DispatcherServlet要绑定spring的配置文件-->
<init-param>
<param-name>contextConfigLocation</param-name>
<!--
classpath:只会到你的class路径中查找找文件;
classpath*:不仅包含class路径,还包括jar文件中(class路径)进行查找。
-->
<param-value>classpath:applicationContext.xml</param-value>
</init-param>
<!--启动级别
正数值越小启动级别越高
如果为负数,则servlet被请求时才加载
必须为整数,不为整数则报错
-->
<load-on-startup>1</load-on-startup>
</servlet>
<!--
在springMVC中,/和/*的区别
/:只匹配所有的请求,不会去匹配jsp页面
/*:匹配所有的请求,包括jsp页面
-->
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
2.字符过滤
<!--2.springmvc的过滤器-->
<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过期时间
<!--4.Session过期时间-->
<session-config>
<!--15分钟-->
<session-timeout>15</session-timeout>
</session-config>
4.完整代码
<?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 这个是SpringMVC的核心:请求分发器(前端控制器)-->
<servlet>
<servlet-name>springMVC</servlet-name>
<!--这是spring自己写好的-->
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--DispatcherServlet要绑定spring的配置文件-->
<init-param>
<param-name>contextConfigLocation</param-name>
<!--
classpath:只会到你的class路径中查找找文件;
classpath*:不仅包含class路径,还包括jar文件中(class路径)进行查找。
-->
<param-value>classpath:applicationContext.xml</param-value>
</init-param>
<!--启动级别
正数值越小启动级别越高
如果为负数,则servlet被请求时才加载
必须为整数,不为整数则报错
-->
<load-on-startup>1</load-on-startup>
</servlet>
<!--
在springMVC中,/和/*的区别
/:只匹配所有的请求,不会去匹配jsp页面
/*:匹配所有的请求,包括jsp页面
-->
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--2.springmvc的过滤器-->
<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.启动spring工厂-->
<!--<listener>-->
<!-- <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>-->
<!--</listener>-->
<!--<context-param>-->
<!-- <param-name>contextConfigLocation</param-name>-->
<!-- <param-value>classpath:applicationContext.xml</param-value>-->
<!--</context-param>-->
<!--4.Session过期时间-->
<session-config>
<!--15分钟-->
<session-timeout>15</session-timeout>
</session-config>
</web-app>
2.SpringMVC层
spring-mvc.xml
1.自动扫描
<context:component-scan base-package="com.blb.controller"/>
2.注解驱动
<mvc:annotation-driven/>
3.静态资源过滤
<mvc:default-servlet-handler/>
4.视图解析器
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
id="internalResourceViewResolver">
<!-- 前缀 -->
<property name="prefix" value="/WEB-INF/jsp/" />
<!-- 后缀 -->
<property name="suffix" value=".jsp" />
</bean>
5.完整代码
<?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
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--固定代码-->
<!-- 1.自动扫描包,让指定包下的注解生效,由IOC容器统一管理 -->
<context:component-scan base-package="shuangma.controller"/>
<!-- 2.静态资源过滤 -->
<mvc:default-servlet-handler/>
<!--
3.支持mvc注解驱动
在spring中一般采用@RequestMapping注解来完成映射关系
要想使@RequestMapping注解生效
必须向上下文中注册DefaultAnnotationHandlerMapping
和一个AnnotationMethodHandlerAdapter实例
这两个实例分别在类级别和方法级别处理。
而annotation-driven配置帮助我们自动完成上述两个实例的注入。
-->
<mvc:annotation-driven />
<!--视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
id="internalResourceViewResolver">
<!-- 前缀 -->
<property name="prefix" value="/WEB-INF/jsp/" />
<!-- 后缀 -->
<property name="suffix" value=".jsp" />
</bean>
</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="classpath:spring-dao.xml"/>
<import resource="classpath:spring-service.xml"/>
<import resource="classpath:spring-mvc.xml"/>
</beans>
5.Controller 和 视图层编写
1.查询书籍功能
- 1.Controller层
BookController.java
@Controller
@RequestMapping("/book")
public class BookController {
//controller调用service层
@Autowired
@Qualifier("BookServiceImpl")
private BookService bookService;
//查询全部的书籍,并返回到书籍展示页面
@RequestMapping("/allBook")
public String list(Model model){
List<Books> list = bookService.queryAllBook();
model.addAttribute("list",list);
return "allBook";
}
}
- 2.视图层
添加allbook.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.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<%--边框--%>
<div class="container">
<%--清除浮动--%>
<div class="row clearfix">
<%--把屏幕分成12份--%>
<div class="col-md-12 column">
<div class="page-header">
<h1>
<small>书籍列表--显示所有书籍</small>
</h1>
</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="${list}">
<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>
添加index.jsp页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>首页</title>
<!-- 引入 Bootstrap -->
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<style type="text/css">
a {
text-decoration: none;
color: black;
font-size: 18px;
}
h3 {
width: 180px;
height: 38px;
margin: 100px auto;
text-align: center;
line-height: 38px;
background: deepskyblue;
border-radius: 4px;
}
</style>
</head>
<body>
<h3>
<a href="${pageContext.request.contextPath}/book/allBook">进入书籍页面</a>
</h3>
</body>
</html>
将三个文件放到WEB-INF目录下
查看WEB-INF下的lib的依赖是否被添加
2.增加书籍功能
- 1.Controller层
添加到BookController.java
//跳转到增加书籍页面
@RequestMapping("/toAddBook")
public String toAddPaper(){
return "addBook";
}
//添加书籍的请求
@RequestMapping("/addBook")
public String addBook(Books books){
bookService.addBook(books);
return "redirect:/book/allBook";//重定向到 @RequestMapping("/allBook")请求
}
- 2.视图层
修改allbook.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>
<%--<meta name="viewport" content="width=device-width, initial-scale=1.0">--%>
<!-- 引入 Bootstrap -->
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<%--边框--%>
<div class="container">
<%--清除浮动--%>
<div class="row clearfix">
<%--把屏幕分成12份--%>
<div class="col-md-12 column">
<div class="page-header">
<h1>
<small>书籍列表--显示所有书籍</small>
</h1>
</div>
</div>
</div>
<div class="row">
<div class="col-md-4 column">
<a class="btn btn-primary" href="${pageContext.request.contextPath}/book/toAddBook">新增书籍</a>
</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="${list}">
<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>
添加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>
<%--<meta name="viewport" content="width=device-width, initial-scale=1.0">--%>
<!-- 引入 Bootstrap -->
<link href="https://cdn.bootcss.com/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">
<h1>
<small>新增书籍</small>
</h1>
</div>
</div>
</div>
<form action="${pageContext.request.contextPath}/book/addBook"
method="post">
<div class="form-group">
<label>书籍名称:</label>
<%--name属性必须与实体类和数据库一致 required让用户必须填,不填提示请添加此字段--%>
<input type="text" name="bookName" class="form-control" required><br>
</div>
<div class="form-group">
<label>书籍数量:</label>
<input type="text" name="bookCounts" class="form-control" required><br>
</div>
<div class="form-group">
<label>书籍详情:</label>
<input type="text" name="detail" class="form-control" required><br>
</div>
<div class="form-group">
<input type="submit" class="form-control" value="添加">
</div>
<div class="form-group">
<input type="button" value="返回" class="form-control" onclick="javascript:history.back();">
</div>
</form>
</div>
3.修改书籍功能
-
1.Controller层
添加到BookController.java
//跳转到修改页面
@RequestMapping("/toUpdateBook")
public String toUpdatePaper(int id,Model model){
Books books=bookService.queryBookById(id);
model.addAttribute("book",books);
return "updateBook";
}
//修改书籍
@RequestMapping("/updateBook")
public String updateBook(Books books){
bookService.updateBook(books);
return "redirect:/book/allBook";
}
- 2.视图层
修改allbook.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>
<%--<meta name="viewport" content="width=device-width, initial-scale=1.0">--%>
<!-- 引入 Bootstrap -->
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<%--边框--%>
<div class="container">
<%--清除浮动--%>
<div class="row clearfix">
<%--把屏幕分成12份--%>
<div class="col-md-12 column">
<div class="page-header">
<h1>
<small>书籍列表--显示所有书籍</small>
</h1>
</div>
</div>
</div>
<div class="row">
<div class="col-md-4 column">
<a class="btn btn-primary" href="${pageContext.request.contextPath}/book/toAddBook">新增书籍</a>
</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>
<th>操作</th>
</tr>
</thead>
<%--书籍从数据库中查询出来,从这个list中遍历出来--%>
<tbody>
<c:forEach var="book" items="${list}">
<tr>
<td>${book.bookID}</td>
<td>${book.bookName}</td>
<td>${book.bookCounts}</td>
<td>${book.detail}</td>
<td>
<a href="${pageContext.request.contextPath}/book/toUpdateBook?id=${book.getBookID()}">修改</a>
|
<a href="${pageContext.request.contextPath}/book/deleteBook/${book.getBookID()}"> 删除</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
添加updateBook.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>
<%--<meta name="viewport" content="width=device-width, initial-scale=1.0">--%>
<!-- 引入 Bootstrap -->
<link
href="https://cdn.bootcss.com/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">
<h1>
<small>修改信息</small>
</h1>
</div>
</div>
</div>
<form action="${pageContext.request.contextPath}/book/updateBook"
method="post">
<%--出现的问题:我们提交了修改的SQL语句请求,但是修改失败,初次考虑是事务的问题,配置完毕,依旧失败--%>
<input type="hidden" name="bookID" value="${book.getBookID()}"/>
<div class="form-group">
<label>书籍名称:</label>
<%--name属性必须与实体类和数据库一致 required让用户必须填,不填提示请添加此字段--%>
<input type="text" name="bookName" class="form-control" value="${book.getBookName()}" required><br>
</div>
<div class="form-group">
<label>书籍数量:</label>
<input type="text" name="bookCounts" class="form-control" value="${book.getBookCounts()}" required><br>
</div>
<div class="form-group">
<label>书籍详情:</label>
<input type="text" name="detail" class="form-control" value="${book.getDetail() }" required><br>
</div>
<div class="form-group">
<input type="submit" class="form-control" value="修改">
</div>
<div class="form-group">
<input type="button" value="返回" class="form-control" onclick="javascript:history.back();">
</div>
</form>
</div>
</body>
</html>
4.删除书籍功能
- Controller层
//删除书籍
@RequestMapping("/deleteBook/{bookId}")
public String deleteBook(@PathVariable("bookId") int id){
bookService.deleteBookById(id);
return "redirect:/book/allBook";
}
5.根据书名查询书籍功能
- 1.Controller层
//查询书籍
@RequestMapping("/queryBook")
public String queryBook(String queryBookName,Model model){
Books books = bookService.queryBookByName(queryBookName);
List<Books> list=new ArrayList<>();
list.add(books);
if(books==null){
list=(bookService.queryAllBook());
model.addAttribute("error","未找到该书籍");
}
model.addAttribute("list",list);
return "allBook";
}
- 2.视图层
修改allbook.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.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<%--边框--%>
<div class="container">
<%--清除浮动--%>
<div class="row clearfix">
<%--把屏幕分成12份--%>
<div class="col-md-12 column">
<div class="page-header">
<h1>
<small>书籍列表--显示所有书籍</small>
</h1>
</div>
</div>
</div>
<div class="row">
<div class="col-md-4 column">
<a class="btn btn-primary" href="${pageContext.request.contextPath}/book/toAddBook">新增书籍</a>
<a class="btn btn-primary" href="${pageContext.request.contextPath}/book/allBook">显示全部书籍</a>
</div>
<div class="col-md-4 column"></div>
<div class="col-md-4 column">
<form class="form-inline" action="${pageContext.request.contextPath}/book/queryBook" method="post"
style="float: right">
<span style="color:red;font-weight: bold">${error}
</span>
<input type="text" name="queryBookName" class="form-control" placeholder="请输入要查询的书名" required>
<input type="submit" value="查询" class="btn btn-primary">
</form>
</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>
<th>操作</th>
</tr>
</thead>
<%--书籍从数据库中查询出来,从这个list中遍历出来--%>
<tbody>
<c:forEach var="book" items="${list}">
<tr>
<td>${book.bookID}</td>
<td>${book.bookName}</td>
<td>${book.bookCounts}</td>
<td>${book.detail}</td>
<td>
<a href="${pageContext.request.contextPath}/book/toUpdateBook?id=${book.getBookID()}">修改</a>
|
<a href="${pageContext.request.contextPath}/book/deleteBook/${book.getBookID()}"> 删除</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
- 3.dao层
添加到BookMapper接口里
//通过书名查询一本书
Books queryBookByName(@Param("bookName") String bookName);
添加到BookMapper.xml文件里
<!--通过书名查询一本书-->
<select id="queryBookByName" resultType="Books">
SELECT * from books where bookName=#{bookName}
</select>
- 4.service层
添加到BookService接口里
//通过书名查询一本书
Books queryBookByName(String bookName);
添加到BookService实现类里
@Override
public Books queryBookByName(String bookName) {
return bookMapper.queryBookByName(bookName);
}