完成了springboot搭建怎么能少了最基础的crud。 这里实现简单的增删改查,用到thymeleaf,mybatis,pagehelper等。
废话不多说,下面开始进入正题:
新建springboot项目后,建各种包目录结构,下面是我最终的目录结构
进行一一说明:
sql脚本不多说
CREATE TABLE `article` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) DEFAULT NULL,
`mdContent` text COMMENT 'md文件源码',
`htmlContent` text COMMENT 'html源码',
`summary` text,
`cid` int(11) DEFAULT NULL,
`uid` int(11) DEFAULT NULL,
`publishDate` datetime DEFAULT NULL,
`editTime` datetime DEFAULT NULL,
`state` int(11) DEFAULT NULL COMMENT '0表示草稿箱,1表示已发表,2表示已删除',
`pageView` int(11) DEFAULT '0',
PRIMARY KEY (`id`),
KEY `cid` (`cid`),
KEY `uid` (`uid`),
CONSTRAINT `article_ibfk_1` FOREIGN KEY (`cid`) REFERENCES `category` (`id`),
CONSTRAINT `article_ibfk_2` FOREIGN KEY (`uid`) REFERENCES `user` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=123 DEFAULT CHARSET=utf8;
model为实体类,不多解释
private int id;
private String title;
private String mdContent;
private String htmlContent;
private String summary;
private int cid;
private int uid;
private Date publishDate;
private Date editTime;
private int state;
private int pageView;
...get
...set方法
service层,service层为业务层,用来实现业务逻辑
@Select为MyBatis注解,是将SQL直接注解写在接口上 。
这种方式的优点是:对于需求比较简单的系统,效率较高。 缺点是:当SQL有变化时都需要重新编译代码。
@Mapper
public interface ArtcileMapper {
@Select("select * from article where title like concat('%',#{title},'%')")
List<Article> findArtcleBytitle(String title);
@Update ("update article set " +
"title = #{title}," +
"mdContent = #{mdContent}," +
"summary = #{summary} ," +
"state = #{state} " +
"where id=#{id} ")
public int updateArtcile(Article article);
@Delete (" delete from article where id= #{id} ")
public int deleteArtcile(Integer id);
@Insert ("insert into article (id,title,mdContent,summary,state) " +
"values (#{id},#{title},#{mdContent},#{summary},#{state})")
public int insertArtcile(Article article);
@Select("select * from article ")
public List<Article> ListArticle();
@Select("select * from article where id=#{id}")
public Article getArticleById(Integer id) ;
}
controller层为控制层,主要处理外部请求。
调用service层,将service层返回的BO/DO转化为DTO/VO并封装成统一返回对象返回给调用方。如果返回数据用于前端模版渲染则返回VO,否则一般返回DTO。
注意头部是@Controller,非@RestController否则无法返回模版,返回的是字符串,俩者区别自行查询。
@Controller
public class HelloController {
@Resource
private ArtcileMapper artcileMapper;
//添加页面
@RequestMapping ( "add" )
public String add() {
return "add";
}
//查找(用于查询)
@RequestMapping ( "getArticle" )
public String getArticle(int id, Model model) throws Exception {
Article article = artcileMapper.getArticleById(id);
model.addAttribute("article", article);
return "articleShow";
}
//添加
@RequestMapping ( "addArticle" )
public String listArticle(Article article, BindingResult bindingResult) throws Exception {
boolean flag = artcileMapper.insertArtcile(article) > 0;
return "redirect:listArticle";
}
//删除
@RequestMapping ( "deleteArticle" )
public String deleteArticle(Article article) throws Exception {
artcileMapper.deleteArtcile(article.getId());
return "redirect:listArticle";
}
//修改
@RequestMapping ( "updateArticle" )
public String updateArticle(Article article) throws Exception {
boolean flag = artcileMapper.updateArtcile(article) > 0;
return "redirect:listArticle";
}
//查找(用于修改)
@RequestMapping ( "findArticle" )
public String findArticle(int id, Model model) throws Exception {
Article article = artcileMapper.getArticleById(id);
model.addAttribute("article", article);
return "modify";
}
//遍历
@RequestMapping ( "/listArticle" )
public String listArticle(@RequestParam ( value = "title", defaultValue = "" ) String title,
Model model, @RequestParam ( value = "start", defaultValue = "1" ) int start,
@RequestParam ( value = "size", defaultValue = "5" ) int size) throws Exception {
PageHelper.startPage(start, size);
List<Article> articleList = artcileMapper.findArtcleBytitle(title);
PageInfo<Article> page = new PageInfo<>(articleList);
System.out.println("总数量:" + page.getTotal());
System.out.println("当前页查询记录:" + page.getList().size());
System.out.println("当前页码:" + page.getPageNum());
System.out.println("每页显示数量:" + page.getPageSize());
System.out.println("总页:" + page.getPages());
model.addAttribute("pages", page);
model.addAttribute("title", title);
return "index";
}
}
好了,Java代码基本已经实现了,代码应该都能看懂。下面开始进行模版thymeleaf实现。
index.html也就是我们的列表页,thymeleaf模版必须包含xmlns:th="http://www.thymeleaf.org"
代码如下
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>表单</title>
</head>
<script th:src="@{/js/jquery-3.4.1.min.js}"></script>
<script type="text/javascript" th:src="@{/js/index.js}"></script>
<body>
<div align="center">
<form action="#" th:action="@{/listArticle}" method="post">
<label for="title">全表查询:</label>
<input id="title" name="title" th:value="${title}">
<button id="search-btn" name="search-btn">搜索</button>
</form>
<a th:href="@{/add}">添加内容</a>
<a th:href="@{/listArticle}">刷新全部数据</a>
<table width="100%" border="1">
<tr align="center">
<td width="20%">标题</td>
<td width="20%">概述</td>
<td width="30%">内容</td>
<td width="10%">状态</td>
<td colspan="2" width="20%">操作</td>
</tr>
<tr align="center" th:each="list: ${pages.list}">
<td><a th:href="@{/getArticle(id=${list.id})}">[[${list.title}]]</a></td>
<td th:text="${list.summary}"></td>
<td th:text="${list.mdContent}"></td>
<td th:text="${list.state}==1?'发布':'未发布'"></td>
<td><a th:href="@{/findArticle(id=${list.id})}">编辑</a></td>
<td><a th:href="@{/deleteArticle(id=${list.id})}">删除</a></td>
</tr>
</table>
</div>
<div align="center">
<a th:unless="${pages.isFirstPage}"
th:href="@{/listArticle(title=${title})}">首 页</a>
<a th:unless="${pages.isFirstPage}"
th:href="@{/listArticle(start=${pages.isHasPreviousPage()}?${pages.getPrePage()}:1, title=${title})}">上一页</a>
<a th:unless="${pages.isLastPage}"
th:href="@{/listArticle(start=${pages.isHasNextPage()}?${pages.getNextPage()}:${pages.getPages()}, title=${title})}">下一页</a>
<a th:unless="${pages.isLastPage}"
th:href="@{/listArticle(start=${pages.getPages()}, title=${title})}">末 页</a>
</div>
<script type="text/javascript">
</script>
</body>
</html>
index.js
$(function () {
var search = $("#search-btn");
search.click(function () {
var name = $("#title");
if (name.val() === null || name.val() === '') {
alert("请输入~");
return;
}
console.log(search);
search.submit();
})
});
其他类似增查改,没啥好说的,都一样,就不贴了,下面会放github地址。
模版好了,还有最重要的一点,配置文件
spring.datasource.url=jdbc:mysql://localhost/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=true
spring.datasource.username=root
spring.datasource.password=12345678
#
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#测试获取配置信息
#article.title=\u6211\u662f\u4e2d\u6587\u914d\u7f6e\u9879
#article.mdContent=test1211w21w
#spring.thymeleaf.mode=HTML5
#spring.thymeleaf.encoding=UTF-8
#spring.thymeleaf.servlet.content-type=text/html
#缓存设置为false, 这样修改之后马上生效,便于调试
spring.thymeleaf.cache=false
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.alpha</groupId>
<artifactId>springboottest1</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboottest1</name>
<description>project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- servlet依赖. -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<!-- tomcat的支持.-->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<!-- pageHelper 用于分页 -->
<!-- <dependency>-->
<!-- <groupId>com.github.pagehelper</groupId>-->
<!-- <artifactId>pagehelper</artifactId>-->
<!-- <version>4.1.6</version>-->
<!-- </dependency>-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.5</version>
</dependency>
<!--引入JQuery库-->
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<fork>true</fork>
</configuration>
</plugin>
</plugins>
</build>
</project>
这里重点说明springboot用必须用pagehelper-spring-boot-starter这个分页,用下面这个是不起效果的,大家可以试一下。
<!-- pageHelper 用于分页 -->
<!-- <dependency>-->
<!-- <groupId>com.github.pagehelper</groupId>-->
<!-- <artifactId>pagehelper</artifactId>-->
<!-- <version>4.1.6</version>-->
<!-- </dependency>-->
好了,以上完成可以启动了。浏览器输入http://localhost:8080/listArticle,页面不是太丑,凑合着看吧。
add
github地址:https://github.com/Alpha470/springboot-mybatis-thymeleaf-crud.git