目录
3.1编写spring和dao层的:spring-dao.xml配置文件
3.2编写spring和service层的:spring-service.xml配置文件
1. 环境搭建
1. 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(100) 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,'从进门到坐牢')
1.2依赖注入
(10个依赖,1个过滤器)
<dependencies>
<!-- 测试驱动 -->
<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>
<!-- 数据库连接池c3p0 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.22</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>
</dependencies>
<!--负责将配置文件复制到编译目录中-->
<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>
1.3建立基本结构配置框架
三层架构:pojo、dao、service、controller
2.mybatis层编写
2.1数据库配置文件
database.properties (根据自己的mysql数据库存放位置,相关账号和密码填写)
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?useSSL=true&useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=123456
2.2编写pojo实体类
这里运用到了lombok依赖,如果不喜欢可以手动添加有参、无惨构造器、set/get方法、toString
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Books {
private int bookID;
private String bookName;
private int bookCounts;
private String detail;
}
2.3编写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>
<!--别名-->
<typeAliases>
<package name="com.yun.pojo"/>
</typeAliases>
<!--绑定BookMapper.xml配置文件-->
<mappers>
<mapper class="com.yun.dao.BookMapper"/>
</mappers>
</configuration>
2.4编写dao层的Mapper接口和xml文件
接口
import java.util.List;
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();
}
xml文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.yun.dao.BookMapper">
<insert id="addBook" parameterType="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="Books">
update ssmbuild.books set bookName=#{bookName},bookCounts=#{bookCounts},detail=#{detail}
where bookID=#{bookID}
</update>
<select id="queryBookById" resultType="Books">
select * from ssmbuild.books where bookID=#{bookID}
</select>
<select id="queryAllBook" resultType="Books">
select * from ssmbuild.books
</select>
</mapper>
2.5编写service层
2.5.1接口
public interface BookService {
int addBook(Books book);
int deleteBookById(int id);
int updateBook(Books book);
Books queryBookById(int id);
List<Books> queryAllBook();
}
2.5.2接口实现类
public class BookServiceImpl implements BookService {
//service层调用dao层,设置set接口,方便spring管理
private BookMapper bookMapper;
public void setBookMapper(BookMapper bookMapper) {
this.bookMapper = bookMapper;
}
public int addBook(Books book) {
return bookMapper.addBook(book);
}
public int deleteBookById(int id) {
return bookMapper.deleteBookById(id);
}
public int updateBook(Books book) {
return bookMapper.updateBook(book);
}
public Books queryBookById(int id) {
return bookMapper.queryBookById(id);
}
public List<Books> queryAllBook() {
return bookMapper.queryAllBook();
}
}
3.Spring层编写
数据源使用c3p0连接池
3.1编写spring和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="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配置文件-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
<!--扫描dao接口包,动态实现dao注入到spring中-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--注入sqlSessionFactory-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!--给出需要扫描dao接口包-->
<property name="basePackage" value="com.yun.dao"/>
</bean>
</beans>
3.2编写spring和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: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. 扫描service层-->
<context:component-scan base-package="com.yun.service"/>
<!--2. 将BookServiceImpl注入到容器IOC中-->
<bean id="BookServiceImpl" class="com.yun.service.BookServiceImpl">
<property name="bookMapper" ref="bookMapper"/>
</bean>
<!--配置事务管理器-->
<bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--注入数据库连接池-->
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>
4.springMVC层编写
4.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">
<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>
4.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: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 https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--扫描宝-->
<context:component-scan base-package="com.yun.controller"/>
<!--注解驱动-->
<mvc:annotation-driven/>
<!--静态资源默认配置-->
<mvc:default-servlet-handler/>
<!--视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
5.编写controller层
@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";
}
}
写到这里先进行代码的测试,看看是否有BUG
测试
创建addBook.jsp页面
在首页index.jsp页面中添加跳转链接
测试成功
测试成功,说明写的代码没有问题,接下来对其他功能进行编写
6.美化页面
6.1编写首页
对首页进行改造
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<%--头文件,编辑表头格式--%>
<head>
<title>首页</title>
<style type="text/css">
<%--text-decoration:下划线的颜色
color:字体的颜色
font-size:字体大小
在前端中“:”相当于赋值
--%>
a {
text-decoration: none;
color: black;
font-size: 18px;
}
/*
width、height表示边框的宽高
margin:外边距(auto边框水平居中)
text-align: center:文本在边框中左右居中
line-height:文本离变宽顶部的距离
background:背景颜色
border-radius:边框的倒角
*/
h3{
width: 180px;
height: 38px;
margin: 100px auto;
text-align: center;
line-height: 38px;
background: greenyellow;
border-radius: 4px;
}
</style>
</head>
<body>
<h3>
<%--<href后面加的是绝对地址>+表头名称--%>
<a href="${pageContext.request.contextPath}/book/allBook">点击进入列表页</a>
</h3>
</body>
</html>
如图所示,尺寸,大小,颜色可根据自己喜爱调整
6.2查询所有书籍页面
点击进入列表页直接跳转显示所有书籍
<%@ 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="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<%--栅格系统,将屏幕分成好几份,然后包在一个Container容器里--%>
<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-4 column">
<%--class="bth bth-primary":设置外框背景,美化新增书籍按钮--%>
<a href="${pageContext.request.contextPath}/book/toAddBook">新增书籍</a>
</div>
</div>
<div class="row clearfix">
<div class="col-md-12 column">
<%--创建表格
table-hover隔行变色
table-striped显示表格
--%>
<table class="table table-hover table-striped">
<%--表头th--%>
<thead>
<tr>
<th>书籍编号</th>
<th>书籍名字</th>
<th>书籍数量</th>
<th>书籍详情</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<%--表的内容,书籍从数据中查询出来,从list中遍历出来
var:list里面的每一个值,items:从list里取数据
头部是th,身体是td
--%>
<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/toUpateBook/${book.bookID}">修改</a>
|
<a href="${pageContext.request.contextPath}/book/deleteBook/${book.bookID}">删除</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
如图所示
6.3添加书籍页面
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>添加书籍</title>
<<link href="http://cdn.static.runoob.com/libs/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="big">
<%--required:为空提交会提示--%>
<div class="form-group">
<label>书籍名称</label>
<input type="text" name="bookName" class="form-control" required>
</div>
<div class="form-group">
<label>书籍数量</label>
<input type="text" name="bookCounts" class="form-control" required>
</div>
<div class="form-group">
<label>书籍描述</label>
<input type="text" name="detail" class="form-control" required>
</div>
<div class="form-group">
<%--submit跳转页面--%>
<input type="submit" class="form-control" value="添加">
</div>
</form>
</div>
</body>
</html>
如图所示,增加submit为空提示功能
6.3修改书籍页面
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>修改书籍</title>
<<link href="http://cdn.static.runoob.com/libs/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="box">
<%--required:为空提交会提示--%>
<%--需要配置隐藏域,mysql修改的时候会根据id修改,但是前端不显示id所以需要配置id的隐藏域--%>
<input type="hidden" name="bookID" value="${QBook.bookID}">
<div class="form-group">
<label>书籍名称</label>
<input type="text" name="bookName" class="form-control" value="${QBook.bookName}" required>
</div>
<div class="form-group">
<label>书籍数量</label>
<input type="text" name="bookCounts" class="form-control" value="${QBook.bookCounts}" required>
</div>
<div class="form-group">
<label>书籍描述</label>
<input type="text" name="detail" class="form-control" value="${QBook.detail}" required>
</div>
<div class="form-group">
<%--submit跳转页面--%>
<input type="submit" class="form-control" value="修改">
</div>
</form>
</div>
</body>
</html>
6.4控制器(Controller)控制页面跳转
@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";
}
//跳转到增加书籍页面
@RequestMapping("/toAddBook")
public String toAddPaper(){
return "addBook";
}
//添加书籍的方法
@RequestMapping("/addBook")
public String addPaper(Books books){
System.out.println("addBook:"+books);
bookService.addBook(books);
return "redirect:/book/allBook"; //重定向到@RequestMapping("/allBook")请求
}
//跳转修改页面
@RequestMapping("/toUpateBook/{bookID}")
public String toUpatePaper(@PathVariable("bookID")int id,Model model){
//查询书籍返回到前端
System.out.println(id);
Books books = bookService.queryBookById(id);
model.addAttribute("QBook",books);
return "updateBook";
}
//修改书籍方法
@RequestMapping("/updateBook")
public String updatePaper(Books books){
System.out.println("updateBook:"+books);
bookService.updateBook(books);
return "redirect:/book/allBook";
}
//修改书籍方法
@RequestMapping("/deleteBook/{bookID}")
public String deleteBook(@PathVariable("bookID") int id){
bookService.deleteBookById(id);
return "redirect:/book/allBook";
}
}
以上已完成图书馆里系统的增删改查功能的实现,现在如果需要增加功能可以在原有框架上直接增加即可,如下操作
7.新增根据书名搜索功能
7.1设置前端需要添加的功能(根据书名查找)
<%--跳转到增加书籍页面--%>
<div class="row clearfix">
<div class="col-md-4 column">
<%--class="bth bth-primary":设置外框背景,美化新增书籍按钮--%>
<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>
<div class="col-ma-8 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="请输入要查询的书籍">
<input type="submit" value="查询" class="btn btn-primary">
</form>
</div>
7.2根据功能从底层开始开发
7.2.1从dao层开始
BookMapper接口
Books queryBookByName(@Param("bookName") String bookName);
BookMapper.xml
<select id="queryBookByName" resultType="Books">
select * from ssmbuild.books where bookName = #{bookName}
</select>
7.2.2service层调用dao层
BookService接口
Books queryBookByName(String bookName);
BookServiceImpl实现类
public Books queryBookByName(String bookName) {
return bookMapper.queryBookByName(bookName);
}
7.2.3Controller层调service层
@RequestMapping("/queryBook")
public String queryBook(String queryBookName,Model model){
//将书籍名字传到mysql执行
Books books = bookService.queryBookByName(queryBookName);
System.out.println("bookName:"+queryBookName);
List<Books> list = new ArrayList<Books>();
list.add(books);
if(books == null){
list = bookService.queryAllBook();
model.addAttribute("error","未查到");
}
model.addAttribute("list",list);
return "allBook";
}
以上就已经完成一个按书名查找的功能
这是写好web项目的首页