一个使用SSM框架的简单图书管理系统
主要目的是为熟悉 SSM 框架的开发,完成最为常见的 增删查改 功能;前端较为简略
主页:
添加书籍
修改书籍
删除会从数据库中删除这本书并回到显示所有书籍页面
查询单本书籍
查询书籍未找到时
项目实现如下:
IDEA 、MySQL 8.0.13 、Tomcat7 、Maven3.5.4
要求:需要熟练掌握 MySQL数据库,Spirng,javaWeb 及 MyBatis 知识,简单的前端知识
创建一个存放书籍数据的数据库表
CREATE DATABASE ssm_book;
USE ssm_book;
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 项目:ssm_book,添加 web 的支持
导入相关的 pom 依赖
<dependencies>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.12version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.13version>
dependency>
<dependency>
<groupId>com.mchangegroupId>
<artifactId>c3p0artifactId>
<version>0.9.5.2version>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>servlet-apiartifactId>
<version>2.5version>
dependency>
<dependency>
<groupId>javax.servlet.jspgroupId>
<artifactId>jsp-apiartifactId>
<version>2.2version>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>jstlartifactId>
<version>1.2version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.2version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>2.0.2version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>5.1.9.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>5.1.9.RELEASEversion>
dependency>
dependencies>
Maven 资源过滤设置
<build>
<resources>
<resource>
<directory>src/main/javadirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
<filtering>falsefiltering>
resource>
<resource>
<directory>src/main/resourcesdirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
<filtering>falsefiltering>
resource>
resources>
build>
建立基本结构和配置框架:
创建如下四个包
resources 目录下:
mybatis-config.xml
<configuration>
configuration>
applicationContext.xml
<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>
数据库配置文件 database.properties
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?useSSL=true&useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai
jdbc.username=root
jdbc.password=mysql700
IDEA 关联数据库
编写 MyBatis 的核心配置文件
<configuration>
<typeAliases>
<package name="com.mithrandir.pojo"/>
typeAliases>
<mappers>
<mapper resource="com/mithrandir/dao/BookMapper.xml"/>
mappers>
configuration>
编写数据库对应的实体类 com.kuang.pojo.Books
此处使用 lombok 插件
package com.mithrandir.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;
}
编写 dao 层的 Mapper 接口
public interface BookMapper {
//增加一本书
int addBook(Books books);
//删除一本书
int deleteBookById(@Param("bookId") int id);
//更新一本书
int updateBook(Books books);
//查询一本书
Books queryBookById(@Param("bookId") int id);
//查询全部的书
List<Books> queryAllBook();
}
编写接口对应的 Mapper.xml 文件 BookMapper.xml 。需要导入MyBatis的包:
<mapper namespace="com.mithrandir.dao.BookMapper">
<insert id="addBook" parameterType="Books">
insert into ssm_book.books (bookName,bookCounts,detail)
values (#{bookName},#{bookCounts},#{detail});
insert>
<delete id="deleteBookById" parameterType="int">
delete from ssm_book.books where bookID = #{bookId};
delete>
<update id="updateBook" parameterType="com.mithrandir.pojo.Books">
update ssm_book.books
set bookName=#{bookName}, bookCounts=#{bookCounts}, detail=#{detail}
where bookID=#{bookID};
update>
<select id="queryBookById" parameterType="int" resultType="com.mithrandir.pojo.Books">
select * from ssm_book.books where bookID = #{bookId};
select>
<select id="queryAllBook" resultType="com.mithrandir.pojo.Books">
select * from ssm_book.books;
select>
mapper>
编写 Service 层的接口和实现类
接口:
public interface BookService {
//增加一本书
int addBook(Books books);
//删除一本书
int deleteBookById(int id);
//更新一本书
int updateBook(Books books);
//查询一本书
Books queryBookById(int id);
//查询全部的书
List<Books> queryAllBook();
}
实现类
@Service
public class BookServiceImpl implements BookService{
//service调dao层,组合dao:
private BookMapper bookMapper;
public void setBookMapper(BookMapper bookMapper) {
this.bookMapper = bookMapper;
}
@Override
public int addBook(Books books) {
return bookMapper.addBook(books);
}
@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();
}
}
到此,底层需求操作编写完毕!
配置 Spring整合MyBatis,我们这里数据源使用 c3p0连接池:
编写 Spring 整合 Mybatis 的相关的配置文件:spring-dao.xml
<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">
<context:property-placeholder location="classpath:database.properties"/>
<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="30"/>
<property name="minPoolSize" value="10"/>
<property name="autoCommitOnClose" value="false"/>
<property name="checkoutTimeout" value="10000"/>
<property name="acquireRetryAttempts" value="2"/>
bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:mybatis-config.xml"/>
bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<property name="basePackage" value="com.mithrandir.dao"/>
bean>
beans>
Spring 整合 service层
<?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="com.mithrandir.service"/>
<!--2.将我们的所有业务类,注入到Spring,可以通过配置,或者注解实现-->
<bean id="bookServiceImpl" class="com.mithrandir.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>
Spring层搞定!再次理解一下,Spring就是一个大杂烩,一个容器
添加web支持
web.xml
<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">
<servlet>
<servlet-name>springmvcservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:applicationContext.xmlparam-value>
init-param>
<load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>springmvcservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
<filter>
<filter-name>encodingFilterfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>utf-8param-value>
init-param>
filter>
<filter-mapping>
<filter-name>encodingFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<session-config>
<session-timeout>15session-timeout>
session-config>
web-app>
spring-mvc.xml
<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
http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<mvc:annotation-driven/>
<mvc:default-servlet-handler/>
<context:component-scan base-package="com.mithrandir.controller"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
bean>
beans>
至此,配置文件部分暂时结束
BookController 类编写,方法一:查询全部书籍
@Controller
@RequestMapping("/book")
public class BookController {
//controller层 调用 service层
@Autowired
@Qualifier("bookServiceImpl")
private BookService bookService;
//查询全部的书籍,并返回到一个书籍展示页面
@RequestMapping("/allBook")
public String list(Model model){
List<Books> books = bookService.queryAllBook();
model.addAttribute("list",books);
return "allBook";
}
}
编写首页 index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
首页
进入书籍页面
书籍列表页面 allBook.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
书籍展示
<%--引入BoodStrap--%>
BookController 类编写,方法二:添加书籍
//跳转到增加书籍页面
@RequestMapping("/toAddBook")
public String toAddBook(){
return "addBook";
}
//添加书籍的请求
@RequestMapping("/addBook")
public String addBook(Books books) {
bookService.addBook(books);
return "redirect:/book/allBook"; //重定向到我们的@RequestMapping("/allBook")请求
}
添加书籍页面:addBook.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
书籍展示
<%--引入BoodStrap--%>
BookController 类编写,方法三:修改书籍
//跳转到修改页面
@RequestMapping("/toUpdateBook/{bookID}")
public String toUpdateBook(@PathVariable("bookID") int bookID, Model model){
Books book = bookService.queryBookById(bookID);
model.addAttribute("QBook",book);
return "updateBook";
}
//修改书籍的请求
@RequestMapping("/updateBook")
public String updateBook(Books book){
bookService.updateBook(book);
return "redirect:/book/allBook";
}
修改书籍页面 updateBook.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
修改书籍
<%--引入BoodStrap--%>
修改书籍
BookController 类编写,方法四:删除书籍
//删除书籍
@RequestMapping("/deleteBook/{bookID}")
public String deleteBook(@PathVariable("bookID") int bookID){
bookService.deleteBookById(bookID);
return "redirect:/book/allBook";
}
首先在dao层接口中添加方法
//通过名字查询一本书
Books queryBookByName(String booKName);
在 BookMapper.xml 中添加
<select id="queryBookByName" parameterType="String" resultType="com.mithrandir.pojo.Books">
select * from ssm_book.books where bookName = #{bookName};
select>
同样的,service 层添加方法,很简单,此处略去
controller 层添加方法
//查询书籍
@RequestMapping("/queryBook")
public String queryBook(String queryBookName,Model model){
Books books = bookService.queryBookByName(queryBookName);
if (books == null){
List<Books> booksList = bookService.queryAllBook();
model.addAttribute("list",booksList);
model.addAttribute("error","未查到");
} else {
List<Books> list = new ArrayList<Books>();
list.add(books);
model.addAttribute("list",list);
}
return "allBook";
}
前端页面做对应更改,较为简单,此处略去
至此,开发完成