一,所用工具:
- idea 2019.3.3
- tomcat 7.0.1
- mysql 5.7.19
- maven3.6.3
二,项目编写:
1,编写数据库
/*
SQLyog Ultimate v10.00 Beta1
MySQL - 5.7.19 : Database - ssmbuild
*********************************************************************
*/
/*!40101 SET NAMES utf8 */;
/*!40101 SET SQL_MODE=''*/;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`ssmbuild` /*!40100 DEFAULT CHARACTER SET latin1 */;
USE `ssmbuild`;
/*Table structure for table `books` */
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 AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
/*Data for the table `books` */
insert into `books`(`bookID`,`bookName`,`bookCounts`,`detail`)
values (1,'Java',1,'从入门到放弃'),
(2,'MySQL',10,'从删库到跑路'),
(3,'Linux',5,'从进门到进牢');
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
2,导入pom依赖和Maven资源过滤配置
<!-- 导入依赖-->
<dependencies>
<!--Junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</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.5</version>
</dependency>
<!--Servlet-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<!--JSP-->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
</dependency>
<!--jstl-->
<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.5</version>
</dependency>
<!--Mybatis-Spring-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.5</version>
</dependency>
<!--Spring-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.8.RELEASE</version>
</dependency>
<!--Spring操作数据库,还需要spring-jdbc-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.6.RELEASE</version>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
</dependency>
</dependencies>
<!-- 防止maven配置文件无法被导出或生效-->
<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>
3,创建包结构,如图
4,编写pojo包下的实体类
package com.wj.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @Author: wj
* @Date 2020/12/15 18:53
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Books {
private int bookID;
private String bookName;
private int bookCounts;
private String detail;
}
5,编写dao包下的接口和对应的xml文件
package com.wj.dao;
import com.wj.pojo.Books;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* @Author: wj
* @Date 2020/12/15 18:55
*/
public interface BooksMapper {
// 执行增删改查操作
// 增加一本书
int addBook(Books books);
// 删除一本书
int deleteBook(@Param("id") int bookID);
// 更改一本书信息
int updateBook(Books books);
// 查询一本书
Books queryBook(@Param("id") int bookID);
// 查询所有书
List<Books> selectBooks();
}
<?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.wj.dao.BooksMapper">
<insert id="addBook" parameterType="books">
insert into books(bookName,bookCounts,detail) values (#{bookName},#{bookCounts},#{detail})
where bookID=#{bookID};
</insert>
<delete id="deleteBook" parameterType="int">
delete from books where bookID=#{bookID};
</delete>
<update id="updateBook" parameterType="books">
update books set bookName=#{bookName} where bookID=#{bookID};
</update>
<select id="queryBook" parameterType="int">
slect * from books where bookID=#{bookID}
</select>
<select id="selectBooks" resultType="books">
select * from books;
</select>
</mapper>
6,编写service包用来调用dao包中的方法
package com.wj.service;
import com.wj.pojo.Books;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* @Author: wj
* @Date 2020/12/15 19:12
*/
public interface BookService {
// 执行增删改查操作
// 增加一本书
int addBook(Books books);
// 删除一本书
int deleteBook(@Param("id") int bookID);
// 更改一本书信息
int updateBook(Books books);
// 查询一本书
Books queryBook(@Param("id") int bookID);
// 查询所有书
List<Books> selectBooks();
}
package com.wj.service;
import com.wj.dao.BooksMapper;
import com.wj.pojo.Books;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
/**
* @Author: wj
* @Date 2020/12/15 19:13
*/
public class BookServiceImpl implements BookService{
private BooksMapper booksMapper;
public void setBooksMapper(BooksMapper booksMapper) {
this.booksMapper = booksMapper;
}
public int addBook(Books books) {
return booksMapper.addBook(books);
}
public int deleteBook(int bookID) {
return booksMapper.deleteBook(bookID);
}
public int updateBook(Books books) {
return booksMapper.updateBook(books);
}
public Books queryBook(int bookID) {
return booksMapper.queryBook(bookID);
}
public List<Books> selectBooks() {
return booksMapper.selectBooks();
}
}
7,编写xml相关资源配置文件
(1)mybatis相关的: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>
<typeAliases>
<typeAlias type="com.wj.pojo.Books" alias="books"/>
</typeAliases>
<mappers>
<mapper class="com.wj.dao.BooksMapper"/>
</mappers>
</configuration>
db.properties文档用来写数据库相关的代码
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/ssmbuild?useSSL=true&useUnicode=true&characterEncoding=utf-8
username=root
password=123456
(2)spring层:spring-dao.xml和spring-service.xml(官方文档)
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
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,数据库连接池(c3p0)-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="root"/>
<property name="password" value="${password}"/>
<property name="jdbcUrl" value="${url}"/>
<property name="driverClass" value="${driver}"/>
<property name="autoCommitOnClose" value="false"/>
<property name="maxPoolSize" value="30"/>
<property name="minPoolSize" value="10"/>
<property name="loginTimeout" value="500"/>
</bean>
<!-- 3,配置sqlSessionFactory对象-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<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.wj.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
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相关的bean-->
<context:component-scan base-package="com.wj.service"/>
<!-- 2,BookServiceImpl注入到IOC容器中-->
<bean id="BookServiceImpl" class="com.wj.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>
(3)springMvc层,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,开启SpringMvc注解驱动-->
<mvc:annotation-driven/>
<!-- 2,静态资源默认servlet配置-->
<mvc:default-servlet-handler/>
<!-- 3,配置jsp显示ViewResolver视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!-- 4,扫描web相关的bean-->
<context:component-scan base-package="com.wj.controller"/>
</beans>
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">
<!-- DispatcherServlet-->
<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>
<!-- encodingFilter-->
<filter>
<filter-name>encoding</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>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- session过期时间-->
<session-config>
<session-timeout>15</session-timeout>
</session-config>
</web-app>
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"
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">
<import resource="spring-service.xml"/>
<import resource="spring-dao.xml"/>
<import resource="spring-mvc.xml"/>
</beans>
8,编写业务代码controller类
(1)查询全部书籍
package com.wj.controller;
import com.wj.pojo.Books;
import com.wj.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
/**
* @Author: wj
* @Date 2020/12/16 12:24
*/
@Controller
@RequestMapping("/book")
public class BookController {
@Autowired
@Qualifier("BookServiceImpl")
private BookService bookService;
@RequestMapping("/allBook")
public String list(Model model){
List<Books> list = bookService.selectBooks();
model.addAttribute("list",list);
return "allBook";
}
}
(2)编写首页index.jsp
<%--
Created by IntelliJ IDEA.
User: 23967
Date: 2020/12/15
Time: 18:49
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>首页</title>
<style>
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>
(3)书籍列表展示页allBook.jsp
<%--
Created by IntelliJ IDEA.
User: 23967
Date: 2020/12/16
Time: 12:29
To change this template use File | Settings | File Templates.
--%>
<%@ 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>
<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>
<tbody>
<c:forEach var="book" items="${requestScope.get('list')}">
<tr>
<td>${book.getBookID()}</td>
<td>${book.getBookName()}</td>
<td>${book.getBookCounts()}</td>
<td>${book.getDetail()}</td>
<td>
<a href="${pageContext.request.contextPath}/book/toUpdateBook?id=${book.getBookID()}">更改</a> |
<a href="${pageContext.request.contextPath}/book/del/${book.getBookID()}">删除</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</div>
9,启动Tomcat测试(切记在运行前将项目所需的jar包导入lib目录下)
10,运行结果截图
11,遇到的问题与反思:
spring-mvc.xml中头文件爆红,如图
将方框中内容删除后恢复正常,如图