SSM整合-图书管理
一、环境配置
1.添加pom依赖
<!-- 数据库驱动 https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.30</version>
</dependency>
<!-- 数据库连接池 https://mvnrepository.com/artifact/com.mchange/c3p0 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.5</version>
</dependency>
<!-- servlet https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<!-- jsp https://mvnrepository.com/artifact/javax.servlet/jsp-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<!-- JSTL https://mvnrepository.com/artifact/javax.servlet/jstl -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- mybatis https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.10</version>
</dependency>
<!-- mybatis-spring https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.2</version>
</dependency>
<!-- spring-webmvc https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.22</version>
</dependency>
<!-- spring-jdbc https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.22</version>
</dependency>
----------------------------------------------------------
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
2.配置服务器
添加web框架支持,添加Tomcat9,如果lib没加载,需要手动建一下lib目录,补全目录结构
3.resources中mybatis-config.xml和applicationContext.xml配置
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>
<!-- 配置数据源 spring去做-->
<typeAliases>
<package name="com.hdat.pojo"/>
</typeAliases>
<mappers>
<mapper class="com.hdat.dao.BookMapper"/>
</mappers>
</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
database.properties
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3308/ssmbooks?useSSL=true&useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai
jdbc.username=root
jdbc.password=2595
2.编写实体类—pojo包下Books类
public class Books {
private int id;
private String bookName;
private int bookCounts;
private String detail;
public Books() {
}
public Books(String bookName, int bookCounts, String detail) {
this.bookName = bookName;
this.bookCounts = bookCounts;
this.detail = detail;
}
public Books(int id, String bookName, int bookCounts, String detail) {
this.id = id;
this.bookName = bookName;
this.bookCounts = bookCounts;
this.detail = detail;
}
这里没有写setter和getter 加上就行
3.编写Dao层的Mapper接口
BookMapper接口
public interface BookMapper {
//增加
int addBooks(Books books);
//删除
int deleteBookById(int id);
//更新
int updateBooks(Books books);
//根据书籍名称进行查询
List<Books> queryBooksByName(String bookName);
//查询全部的书
List<Books> queryAllBooks();
}
4.编写Dao层的Mapper接口对应的xml文件
BookMapper.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.hdat.dao.BookMapper">
<insert id="addBooks" parameterType="Books">
INSERT INTO books (bookName,bookCount,detail)
VALUES (#{bookName},#{bookCount},#{detail});
</insert>
<delete id="deleteBookById" parameterType="int">
DELETE FROM books
WHERE id = #{id};
</delete>
<update id="updateBooks" parameterType="Books">
UPDATE books
SET bookName = #{bookName},bookCount - #{bookCount},detail = #{detail}
WHERE id = #{id};
</update>
<select id="queryBooksByName" resultType="Books">
SELECT id,bookName,bookCounts,detail
FROM books
WHERE bookName like concat('%',#{bookName},'%');
</select>
<select id="queryAllBooks" resultType="Books">
SELECT bookName,bookCount,detail
FROM books
</select>
</mapper>
5.编写Service层的接口
BookService接口
public interface BookService {
//增加
int addBooks(Books books);
//删除
int deleteBookById(int id);
//更新
int updateBooks(Books books);
//根据书籍名称查询
List<Books> queryBooksByName(String bookName);
//查询全部的书
List<Books> queryAllBooks();
}
6.编写Service层的实现类
BookServiceImpl类
public class BookServiceImpl implements BookService{
//service层重写dao层的方法 并给一个set入口 方便spring操作 可以加业务逻辑或事务
private BookMapper bookMapper;
public void setBookMapper(BookMapper bookMapper) {
this.bookMapper = bookMapper;
}
@Override
public int addBooks(Books books) {
return bookMapper.addBooks(books);
}
@Override
public int deleteBookById(int id) {
return bookMapper.deleteBookById(id);
}
@Override
public int updateBooks(Books books) {
return bookMapper.updateBooks(books);
}
@Override
public List<Books> queryBooksByName(String bookName) {
return bookMapper.queryBooksByName(bookName);
}
@Override
public List<Books> queryAllBooks() {
return bookMapper.queryAllBooks();
}
}
7.配置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>
<!-- 配置数据源 spring去做-->
<typeAliases>
<package name="com.hdat.pojo"/>
</typeAliases>
<mappers>
<mapper class="com.hdat.dao.BookMapper"/>
</mappers>
</configuration>
三、Spring层
1.Spring整合Mybatis层的dao层
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:database.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}"/>
<!-- 最大连接数-->
<property name="maxPoolSize" value="20"/>
<!-- 连接超时时间-->
<property name="checkoutTimeout" value="10000"/>
</bean>
<!-- 3.sqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!-- 绑定mybatis配置文件-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
<!-- 4.配置dao接口扫描包,动态的实现了Dao接口注入到Spring容器中-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 注入sqlSessionFactory-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!-- 要扫描的dao包-->
<property name="basePackage" value="com.hdat.dao"/>
</bean>
</beans>
2.Spring整合Mybatis层的service层
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:cotext="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下的包-->
<cotext:component-scan base-package="com.hdat.service"/>
<!-- 2.将所有的业务类 注入到spring中, 可以通过配置或注解实现-->
<bean id="BookServiceImpl" class="com.hdat.service.BookServiceImpl">
<property name="bookMapper" ref="bookMapper"/>
</bean>
<!-- 3.声明式事务配置-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 注入事务源-->
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 4.aop事务支持-->
</beans>
四、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">
<!-- DispatchServlet前段控制器-->
<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>
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: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 https://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!-- 1.注解驱动-->
<mvc:annotation-driven/>
<!-- 2.静态资源过滤-->
<mvc:default-servlet-handler/>
<!-- 3.扫描包 controller-->
<context:component-scan base-package="com.hdat.controller"/>
<!-- 4.视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/"/>
<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="spring-dao.xml"/>
<import resource="spring-service.xml"/>
<import resource="spring-mvc.xml"/>
</beans>
五、控制层和视图层
1.controller
BookController类
@Controller
@RequestMapping("/books")
public class BookController {
//controller层调用service层
@Autowired
@Qualifier("BookServiceImpl")
private BookService bookService;
//查询所有的书籍并展示
@RequestMapping("/allBook")
public String list(Model model){
List<Books> booksList = bookService.queryAllBooks();
model.addAttribute("bookslist",booksList);
return "jsp/allBook";
}
//跳转到添加书籍
@RequestMapping("/toAddBook")
public String toAddBook(){
return "jsp/addBook";
}
//添加书籍
@RequestMapping("/addBook")
public String addBook(Books books){
bookService.addBooks(books);
return "redirect:/books/allBook";
}
//跳转到修改书籍
@RequestMapping(value = "/toEditBook/{id}/{bookName}/{bookCounts}/{detail}",method = RequestMethod.GET)
public String toEditBook(@PathVariable int id,@PathVariable String bookName,@PathVariable int bookCounts,@PathVariable String detail,Model model){
Books books = new Books();
books.setId(id);
books.setBookName(bookName);
books.setBookCounts(bookCounts);
books.setDetail(detail);
model.addAttribute("editBook",books);
return "jsp/editBook";
}
//修改书籍
@RequestMapping("/editBook")
public String editBook(Books books){
bookService.updateBooks(books);
return "redirect:/books/allBook";
}
//删除书籍
@RequestMapping("/deleteBook/{id}")
public String deleteBook(@PathVariable int id){
bookService.deleteBookById(id);
return "redirect:/books/allBook";
}
//查询书籍
@RequestMapping("/selectBook")
public String selectBook(String bookName,Model model){
List<Books> booksList = bookService.queryBooksByName(bookName);
model.addAttribute("bookslist",booksList);
return "jsp/allBook";
}
}
2.jsp
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<style>
a{
text-decoration: none;
color: black;
}
.selectallbook{
height: 50px;
width: 120px;
margin: auto;
text-align: center;
text-align-all: center;
background-color:forestgreen;
border-radius: 3px;
}
</style>
<body>
<div class="selectallbook">
<h3>
<a href="${pageContext.request.contextPath}/books/allBook">查看所有书籍</a>
</h3>
</div>
</body>
</html>
allBook.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>添加书籍</title>
<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">
<h1>
<small>添加一本书籍</small>
</h1>
</div>
</div>
<form action="${pageContext.request.contextPath}/books/addBook" method="post">
<div class="form-group">
<label>书籍名称:</label>
<input type="text" class="form-control" name="bookName" required>
</div>
<div class="form-group">
<label>书籍数量:</label>
<input type="text" class="form-control" name="bookCounts" required>
</div>
<div class="form-group">
<label>书籍简介:</label>
<input type="text" class="form-control" name="detail" required>
</div>
<button type="submit" class="btn btn-default">添加</button>
</form>
</div>
</body>
</html>
bookstrap样式的使用
editBook.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>修改书籍</title>
</head>
<body>
<div class="container">
<div class="row clearfix">
<div class="col-md-12 column">
<h1>
<small>修改这本书籍</small>
</h1>
</div>
</div>
<form action="${pageContext.request.contextPath}/books/editBook" method="post">
<input type="hidden" name="id" value="${editBook.id}">
<div class="form-group">
<label>书籍名称:</label>
<input type="text" class="form-control" name="bookName" value="${editBook.bookName}" required>
</div>
<div class="form-group">
<label>书籍数量:</label>
<input type="text" class="form-control" name="bookCounts" value="${editBook.bookCounts}" required>
</div>
<div class="form-group">
<label>书籍简介:</label>
<input type="text" class="form-control" name="detail" value="${editBook.detail}" required>
</div>
<button type="submit" class="btn btn-default">修改</button>
</form>
</div>
</body>
</html>
六、扩展Ajax+拦截器+文件上传与下载
最后感谢未曾相识的师父狂神说-秦疆!致敬