最近这几天都在看关于springboot的内容,每天新会获得点新收获,并且都总结发在公众号中;最后经过不懈努力,不断查找相关网页,解决各种各样的问题,终于搭建出来了个新版的“S(springboot)S(springmvc)M(mybatis)框架”,下面是搭建步骤。
01
在idea中创建springboot项目
在idea编辑器中,点击File->New->Project->Spring Initializr->选择jdk版本为1.8,然后点击Next
然后按照下图修改各个输入框的值,然后点击Next
选择web,勾上spring web
接下来选择sql,勾上对应的jdbc,mybaits和mysql driver,然后点击Next
然后点击Finish,新建完的项目结构如下:
到现在为止,一个崭新的springboot+Maven项目就搭建好了,接下来我们来配置一下pom.xml文件。
02
配置pom.xml文件
由于我们前端需要使用jsp来展示数据,所以pom.xml文件里面需要配置一个编译解析jsp页面的依赖,代码如下:
<!--用于解析jsp页面--> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> </dependency> <dependency> <groupId>org.apache.tomcat</groupId> <artifactId>tomcat-jsp-api</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency>
在首页我这边需要用到jstl来展示数据,所以还需要导入jstl的相关依赖,如下所示:
<!--jstl相关依赖--> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> </dependency>
03
编写application.properties文件
虽然springboot对配置文件简化了很多,但是必要的配置还是要有的, 那么这些配置就都放在了application.properties文件中,也有的项目中是application.yml文件,在这里我们以application.properties文件为例:
首先需要配置一下服务器的端口号,默认为8080,也可以改,代码如下:
#服务器端口号 server.port=8080
配置数据池:
#配置数据池 spring.datasource.url=jdbc:mysql://localhost:3306/schooldb spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.username=root spring.datasource.password=root
配置mybatis的别名:
#起别名 mybatis.type-aliases-package=com.xiongxiong.entity
配置日志信息:
#配置日志 logging.level.com.xiongxiong.dao = debug logging.file.path=log/ logging.file.name=book.log
配置springmvc的内容
#配置springmvc的内容 #页面默认前缀配置 spring.mvc.view.prefix=/ #页面默认后缀配置 spring.mvc.view.suffix=.jsp
这是些基础的配置,如果还有其他扩展,可以自行添加配置信息。
04
搭建底层的三层架构(数据库脚本和结构在文末)
BookManage
在com.xiongxiong下面新建包entity,存放实体类BookManage,按照数据库表中的字段,对应写实体类的属性,最后getter和setter,代码如下:
package com.xiongxiong.entity; import org.springframework.format.annotation.DateTimeFormat; import java.util.Date; public class BookManage { private int bid; private String bname; private String bauthor; @DateTimeFormat(pattern = "yyyy-MM-dd") private Date btime; private int btype; public int getBid() { return bid; } public void setBid(int bid) { this.bid = bid; } public String getBname() { return bname; } public void setBname(String bname) { this.bname = bname; } public String getBauthor() { return bauthor; } public void setBauthor(String bauthor) { this.bauthor = bauthor; } public Date getBtime() { return btime; } public void setBtime(Date btime) { this.btime = btime; } public int getBtype() { return btype; } public void setBtype(int btype) { this.btype = btype; } }
BookManageMapper
在com.xiongxiong中新建包dao,在该包中创建接口BookManageMapper,分别编写增删改以及查询全部和根据编号查询的接口。
package com.xiongxiong.dao; import com.xiongxiong.entity.BookManage; import org.apache.ibatis.annotations.*; import org.springframework.stereotype.Component; import org.springframework.stereotype.Repository; import org.springframework.web.bind.annotation.ResponseBody; import java.util.List; @Mapper //证明是mybatis的mapper文件 @Repository //证明这是dao层 public interface BookManageMapper { @Select("select * from BookManage;") //查询全部 List<BookManage> findBookAll(); @Insert("insert into bookmanage (bname,bauthor,btime,btype) value(#{bname},#{bauthor},#{btime},#{btype});") //添加 int addBook(BookManage bookManage); @Delete("delete from BookManage where bid = #{bid};") //删除 int delBook(int bid); @Update("update bookmanage set bname=#{bname},bauthor=#{bauthor},btime=#{btime},btype=#{btype} where bid = #{bid}") //修改 int updateBook(BookManage bookManage); @Select("select * from bookmanage where bid = #{bid}") //根据编号查询编号 BookManage findBookById(int bid); }
需要注意的是,由于我们统一都使用注解的方式,所以不用在编写SQL映射文件(mapper),所有的sql语句通过注解方式实现,详情请看代码,各个功能都有相应的注释。
IBookManageService和BookManageServiceImpl
同样,在com.xiongxiong包下面创建service包存放业务的接口,在service包下面新建impl包,存放的是业务接口的实现类,代码如下:
IBookManageService
package com.xiongxiong.service; import com.xiongxiong.entity.BookManage; import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Update; import java.util.List; public interface IBookManageService { //查询全部 List<BookManage> findBookAll(); //添加 int addBook(BookManage bookManage); //删除 int delBook(int bid); //修改 int updateBook(BookManage bookManage); //根据编号查询编号 BookManage findBookById(int bid); }
BookManageServiceImpl
package com.xiongxiong.service.impl; import com.xiongxiong.dao.BookManageMapper; import com.xiongxiong.entity.BookManage; import com.xiongxiong.service.IBookManageService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.transaction.annotation.Transactional; import java.util.List; @EnableTransactionManagement //开启事务管理器 @Transactional //配置事务 @Service //证明这是一个service层 public class BookManageServiceImpl implements IBookManageService { //Dao层的接口 @Autowired BookManageMapper bookManageMapper; @Override public List<BookManage> findBookAll() { return bookManageMapper.findBookAll(); } @Override public int addBook(BookManage bookManage) { return bookManageMapper.addBook(bookManage); } @Override public int delBook(int bid) { return bookManageMapper.delBook(bid); } @Override public int updateBook(BookManage bookManage) { return bookManageMapper.updateBook(bookManage); } @Override public BookManage findBookById(int bid) { return bookManageMapper.findBookById(bid); } }
需要注意的是,在实现类中,需要添加开启事务@EnableTransactionManagement和配置事务@Transactional的注解。
在com.xiongxiong下面创建包web,该包中放控制器,在控制器中实现增删改查的功能以及页面之间的跳转,代码如下:
package com.xiongxiong.web; import com.xiongxiong.entity.BookManage; import com.xiongxiong.service.IBookManageService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import java.util.List; @Controller public class IndexController { //创建Service的对象 @Autowired private IBookManageService bookManageService; //默认进入首页 @RequestMapping("default") public String index(Model model) { List<BookManage> bookManageList = bookManageService.findBookAll(); model.addAttribute("bookManageList",bookManageList); return "index"; } //删除 @RequestMapping("delBook") public String delBook(Model model, int bid) { bookManageService.delBook(bid); index(model); return "index"; } //添加 @RequestMapping("addBook") public String addBook(BookManage bookManage, Model model) { bookManageService.addBook(bookManage); index(model); return "index"; } //跳转到添加的页面 @RequestMapping("add") public String add() { return "addBook"; } }
05
创建jsp页面
在main下面新建文件夹webapp,在该文件夹中新建jsp页面就可以,其中我还用到了jquery(下面有下载链接)的环境,放在js目录下面,目录结构如下所示:
jquery-1.12.4.js:点此下载
bootstrap.js:点此下载
创建index.jsp,用来展示查询展示所有数据,查询的功能在控制器IndexController中实现的,下面是代码:
<%-- Created by IntelliJ IDEA. User: 24519 Date: 2021/1/20 Time: 10:38 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@taglib prefix="f" uri="http://java.sun.com/jsp/jstl/fmt" %> <html> <head> <title>首页</title> </head> <body> <h1>图书信息</h1> <table border="1"> <tr> <td>图书名称</td> <td>图书作者</td> <td>购买时间</td> <td>图书分类</td> <td>操作</td> </tr> <c:forEach items="${bookManageList}" var="book"> <tr> <td>${book.bname}</td> <td>${book.bauthor}</td> <td> <f:formatDate value="${book.btime}" pattern="yyyy-MM-dd"></f:formatDate> </td> <td> <c:if test="${book.btype==1}"> 计算机/软件 </c:if> <c:if test="${book.btype==2}"> 小说/文摘 </c:if> <c:if test="${book.btype==3}"> 杂项 </c:if> </td> <td><a href="delBook?bid=${book.bid}">删除</a></td> </tr> </c:forEach> </table> <a href="addBook.jsp" style="color:red">新增图书信息</a> <script src="js/jquery-1.12.4.js" type="text/javascript"></script> <script type="text/javascript"> $(function () { $("tr:even").css("background", "green"); $("tr:first").css("background", "blue"); }); </script> </body> </html>
创建添加信息的jsp页面addBook.jsp,主要用来添加信息,添加的功能在控制器IndexController中实现,还实现了必要的表单验证,下面是代码:
<%-- Created by IntelliJ IDEA. User: 24519 Date: 2021/1/20 Time: 11:35 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <h1>新增图书信息</h1> <form action="addBook" method="post"> 图书名称:<input type="text" name="bname"/><br/> 图书作者:<input type="text" name="bauthor"/><br/> 购买日期:<input type="text" name="btime"/><br/> 图书类别: <select name="btype"> <option value="0">选择所属分类</option> <option value="1">计算机/软件</option> <option value="2">小说/文摘</option> <option value="3">杂项</option> </select><br/> <input type="submit" value="增加图书"/> </form> <script src="js/jquery-1.12.4.js" type="text/javascript"></script> <script type="text/javascript"> $(function () { $("input[type='submit']").click(function () { var bname = $("input[name='bname']").val(); var bauthor = $("input[name='bauthor']").val(); var btime = $("input[name='btime']").val(); var btype = $("input[name='btype']").val(); if (bname == "") { alert("图书名称不能为空"); return false; } if (bauthor == "") { alert("图书作者不能为空"); return false; } var dateinfo = /^[0-9]{4}-[0-1]{1}[0-9]{1}-[0-3]{1}[0-9]{1}/; if (!dateinfo.test(btime)) { alert("日期格式不正确"); return false; } if (btype == 0) { alert("图书分类需要选择"); return false; } }); }); </script> </body> </html>
然后启动,运行,运行结果如下:
控制台日志如下:
日志文件book.log:
数据库脚本:
/* SQLyog Professional v12.08 (32 bit) MySQL - 5.5.27 : Database - schooldb ********************************************************************* */ /*!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*/`schooldb` /*!40100 DEFAULT CHARACTER SET utf8 */; USE `schooldb`; /*Table structure for table `bookmanage` */ DROP TABLE IF EXISTS `bookmanage`; CREATE TABLE `bookmanage` ( `bid` int(11) NOT NULL AUTO_INCREMENT, `bname` varchar(40) NOT NULL, `bauthor` varchar(40) NOT NULL, `btime` datetime NOT NULL, `btype` int(11) NOT NULL, PRIMARY KEY (`bid`) ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8; /*Data for the table `bookmanage` */ insert into `bookmanage`(`bid`,`bname`,`bauthor`,`btime`,`btype`) values (1,'三国演义','罗贯中','2021-09-08 00:00:00',2),(2,'水浒传','施耐庵','2021-09-08 00:00:00',2),(3,'狂人日记','魯迅','2021-09-08 00:00:00',3),(5,'永乐大典','鲁迅','2020-09-08 00:00:00',2); /*Table structure for table `dept` */ DROP TABLE IF EXISTS `dept`; CREATE TABLE `dept` ( `did` int(11) NOT NULL AUTO_INCREMENT, `dname` varchar(50) DEFAULT NULL, PRIMARY KEY (`did`) ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8; /*Data for the table `dept` */ insert into `dept`(`did`,`dname`) values (1,'测试部'),(2,'销售部'),(3,'服务部'),(4,'开发部'),(5,'运营部'); /*Table structure for table `dog` */ DROP TABLE IF EXISTS `dog`; CREATE TABLE `dog` ( `did` int(11) NOT NULL AUTO_INCREMENT, `dname` varchar(50) DEFAULT NULL, `dpass` varchar(50) DEFAULT NULL, PRIMARY KEY (`did`) ) ENGINE=InnoDB AUTO_INCREMENT=1785770044 DEFAULT CHARSET=utf8; /*Data for the table `dog` */ insert into `dog`(`did`,`dname`,`dpass`) values (1,'111','111'),(2,'旺财','123'),(3,'幸福','111'),(4,'财旺','123'),(5,'进钱','111'),(6,'富贵','123'),(1785770043,'黑虎','123'); /*Table structure for table `emp` */ DROP TABLE IF EXISTS `emp`; CREATE TABLE `emp` ( `eid` int(11) NOT NULL AUTO_INCREMENT COMMENT '编号', `ename` varchar(50) DEFAULT NULL COMMENT '姓名', `epass` varchar(50) DEFAULT NULL COMMENT '密码', `edid` int(11) DEFAULT NULL COMMENT '所在部门编号', PRIMARY KEY (`eid`), KEY `fk_deptid` (`edid`), CONSTRAINT `fk_deptid` FOREIGN KEY (`edid`) REFERENCES `dept` (`did`) ) ENGINE=InnoDB AUTO_INCREMENT=38 DEFAULT CHARSET=utf8; /*Data for the table `emp` */ insert into `emp`(`eid`,`ename`,`epass`,`edid`) values (1,'王伟','111',1),(2,'张王','111',1),(4,'张三','111',4),(6,'张方仪','111',1),(7,'张坤鹏','111',1),(9,'翟选浩','123',1),(10,'季淑琦','111',1),(11,'袁康凯','111',1),(12,'丁长琨','111',1),(33,'老赵','123',1),(34,'老王','123',1),(35,'老李','123',1),(36,'小贼','123',1),(37,'老8','123',1); /*Table structure for table `financingproduct` */ DROP TABLE IF EXISTS `financingproduct`; CREATE TABLE `financingproduct` ( `id` varchar(10) NOT NULL, `Risk` int(11) NOT NULL, `Income` varchar(10) NOT NULL, `SaleStarting` datetime NOT NULL, `SaleEnd` datetime DEFAULT NULL, `End` datetime DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; /*Data for the table `financingproduct` */ insert into `financingproduct`(`id`,`Risk`,`Income`,`SaleStarting`,`SaleEnd`,`End`) values ('1',1,'5.68%','2020-04-09 00:00:00','2021-05-09 00:00:00','2029-09-08 00:00:00'),('2',3,'5.68%','2020-04-09 00:00:00','2021-05-09 00:00:00','2029-09-08 00:00:00'),('3',2,'5.3%','2020-04-09 00:00:00','2021-05-09 00:00:00','2029-09-08 00:00:00'),('4',2,'6.8%','2020-04-09 00:00:00','2021-05-09 00:00:00','2029-09-08 00:00:00'),('5',1,'4.98%','2020-04-09 00:00:00','2021-05-09 00:00:00','2029-09-08 00:00:00'); /*Table structure for table `student` */ DROP TABLE IF EXISTS `student`; CREATE TABLE `student` ( `sid` int(11) NOT NULL AUTO_INCREMENT, `sname` varchar(50) DEFAULT NULL, `sphone` varchar(50) DEFAULT NULL, `spass` varchar(50) DEFAULT NULL, `saddress` varchar(50) DEFAULT NULL, `sage` int(11) DEFAULT NULL, PRIMARY KEY (`sid`) ) ENGINE=InnoDB AUTO_INCREMENT=21 DEFAULT CHARSET=utf8; /*Data for the table `student` */ insert into `student`(`sid`,`sname`,`sphone`,`spass`,`saddress`,`sage`) values (1,'张三','15066675713','111','普通',11),(2,'李四','15066675713','222','普通',20),(3,'admin','15066675713','333','管理员',66),(4,'test','15066675713','111','普通',20),(5,'张先生','150','111','普通',12),(6,'张先生','150','111','普通',12),(7,'张先生','150','111','普通',12),(8,'张先生','150','111','普通',12),(9,'张先生','150','111','普通',12),(10,'张先生','150','111','普通',12),(11,'张先生','150','111','普通',12),(12,'张先生','150','111','普通',12),(13,'张先生','150','111','济南',12),(14,'张先生','150','111','普通',12),(15,'张先生','150','111','普通',12),(16,'张先生','150','111','普通',12),(17,'张先生','150','111','普通',12),(18,'张先生','150','111','普通',12),(19,'张先生','150','111','普通',12),(20,'李先生','160','111','普通',13); /*Table structure for table `teacher` */ DROP TABLE IF EXISTS `teacher`; CREATE TABLE `teacher` ( `tid` int(11) NOT NULL AUTO_INCREMENT, `tname` varchar(50) DEFAULT NULL, `tpass` varchar(50) DEFAULT NULL, `tage` int(11) DEFAULT NULL, `tjob` varchar(50) DEFAULT NULL, PRIMARY KEY (`tid`) ) ENGINE=InnoDB AUTO_INCREMENT=805760409 DEFAULT CHARSET=utf8; /*Data for the table `teacher` */ insert into `teacher`(`tid`,`tname`,`tpass`,`tage`,`tjob`) values (1,'张老师','123',25,'数学'),(2,'王老师','123',36,'语文'),(3,'马老师','123',90,'武术'),(4,'高老师','123',32,'外语'),(5,'赵老师','123',24,'体育'),(6,'钱老师','123',36,'未安排'),(7,'钱老师','123',36,'未安排'),(8,'钱老师','123',36,'未安排'),(9,'钱老师','123',36,'未安排'),(10,'钱老师','123',36,'未安排'),(11,'钱老师','123',36,'未安排'),(12,'钱老师','123',36,'未安排'),(13,'钱老师','123',36,'未安排'),(14,'钱老师','123',36,'未安排'),(15,'钱老师','123',36,'未安排'),(16,'钱老师','123',36,'未安排'),(17,'钱老师','123',36,'未安排'),(805760404,'路老师','123',56,'忽悠学'),(805760405,'路老师','123',56,'忽悠学'),(805760406,'翟老师','123456',56,'化学'),(805760407,'贾老师','123456',56,'物理'),(805760408,'潘老师','123456',56,'金融学'); /*!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 */;