源码 + 资源 下载 >>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.mybatis.spring.bootgroupId>
<artifactId>mybatis-spring-boot-starterartifactId>
<version>2.2.1version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<scope>runtimescope>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>1.2.8version>
dependency>
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>1.2.17version>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-thymeleafartifactId>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>fastjsonartifactId>
<version>1.2.79version>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<optional>trueoptional>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=utf8&serverTimezone=GMT
driver-class-name: com.mysql.cj.jdbc.Driver
# 自定义数据源
type: com.alibaba.druid.pool.DruidDataSource
#Spring Boot 默认是不注入这些属性值的,需要自己绑定
#druid 数据源专有配置
initialSize: 5 # 初始连接数
minIdle: 5 # 最小连接数
maxActive: 20 # 最大连接数
maxWait: 60000 # 没有可用连接时,最大等待时间
timeBetweenEvictionRunsMillis: 60000 # 运行时间间隔
minEvictableIdleTimeMillis: 300000 # 连接保持空闲
validationQuery: SELECT 1 FROM DUAL # 检测连接是否有效的SQL
testWhileIdle: true # 申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效。
testOnBorrow: false # 申请连接时执行validationQuery检测连接是否有效,true 配置会降低性能
testOnReturn: false # 归还连接时执行validationQuery检测连接是否有效,true 配置会降低性能。
poolPreparedStatements: false # 不缓存preparedStatement,也就是PSCache。PSCache对支持游标的数据库性能提升巨大,比如说oracle。在mysql下建议关闭。
#配置监控统计拦截的filters,stat:监控统计、log4j:日志记录、wall:防御sql注入
#如果允许时报错 java.lang.ClassNotFoundException: org.apache.log4j.Priority
#则导入 log4j 依赖即可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4j
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
@Configuration
public class DruidConfig {
@Bean
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource druidDataSource(){
return new DruidDataSource();
}
/**
* 配置 Druid 监控管理后台的Servlet;
* 内置 Servlet 容器时没有web.xml文件,所以使用 Spring Boot 的注册 Servlet 方式
* @Bean
* @return
*/
@Bean
public ServletRegistrationBean statViewServlet(){
// 监控页面地址
ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(),"/druid/*");
// 初始化参数
// 这些参数可以在 com.alibaba.druid.support.http.StatViewServlet
// 的父类 com.alibaba.druid.support.http.ResourceServlet 中找到
HashMap<String, String> initParams = new HashMap<>();
// 后台管理界面的登录账号
initParams.put("loginUsername", "admin");
// 后台管理界面的登录密码
initParams.put("loginPassword", "123456");
//后台允许谁可以访问
//initParams.put("allow", "localhost"):表示只有本机可以访问
//initParams.put("allow", ""):为空或者为null时,表示允许所有访问
initParams.put("allow", "");
//deny:Druid 后台拒绝谁访问
//initParams.put("deny", "192.168.1.20");表示禁止此ip访问
//设置初始化参数
bean.setInitParameters(initParams);
return bean;
}
/**
* 配置 web 监控的 filter
* WebStatFilter:用于配置Web和Druid数据源之间的管理关联监控统计
* @return
*/
@Bean
public FilterRegistrationBean webStatFilter(){
FilterRegistrationBean<Filter> bean = new FilterRegistrationBean<>();
bean.setFilter(new WebStatFilter());
// exclusions:设置哪些请求进行过滤排除掉,从而不进行统计
Map<String, String> initParams = new HashMap<>();
initParams.put("exclusions", "*.js,*.css,/druid/*");
bean.setInitParameters(initParams);
// "/**" 表示过滤所有请求
bean.setUrlPatterns(Arrays.asList("/**"));
return bean;
}
}
CREATE TABLE `article` (
`id` int(10) NOT NULL AUTO_INCREMENT COMMENT 'int文章的唯一ID',
`author` varchar(50) NOT NULL COMMENT '作者',
`title` varchar(100) NOT NULL COMMENT '标题',
`content` longtext NOT NULL COMMENT '文章的内容',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
字段 | 类型 | 备注 |
---|---|---|
id | int | 文章的唯一ID |
author | varchar | 作者 |
title | varchar | 标题 |
content | longtext | 文章的内容 |
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Article implements Serializable {
/**
* 文章的唯一ID
*/
private int id;
/**
* 作者名
*/
private String author;
/**
* 标题
*/
private String title;
/**
* 文章的内容
*/
private String content;
}
@Repository
public interface ArticleMapper {
/**
* 查询所有的文章
* @return
*/
List<Article> queryArticles();
/**
* 新增一篇文章
* @param article
* @return
*/
int addArticle(Article article);
/**
* 根据id查询文章
* @param id
* @return
*/
Article getArticleById(int id);
/**
* 根据id删除文章
* @param id
* @return
*/
int deleteArticleById(int id);
}
mapper.xml配置
resources/mybatis/mapper
目录下
<mapper namespace="com.tuwer.mapper.ArticleMapper">
<select id="queryArticles" resultType="Article">
select * from mybatis.article
select>
<select id="getArticleById" resultType="Article">
select * from mybatis.article where id = #{id}
select>
<insert id="addArticle" parameterType="Article">
insert into mybatis.article (author,title,content) values (#{author},#{title},#{content});
insert>
<delete id="deleteArticleById" parameterType="int">
delete from mybatis.article where id = #{id}
delete>
mapper>
mybatis:
# 实体类别名
type-aliases-package: com.tuwer.pojo
# 映射文件路径
mapper-locations: classpath:/mybatis/mapper/*.xml
下载 editor.md
地址:https://github.com/pandao/editor.md/archive/master.zip
resources\static
目录下新建 editormd
目录,把解压后的部分文件复制到 editormd
目录中editormd
目录下建js
目录,放对应js文件;其中 jquery.min.js
文件在下载包的 examples\js
目录下在
resources\templates
目录下建article
目录,存入文章页面
<html class="x-admin-sm" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>添加文章title>
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width,user-scalable=yes, minimum-scale=0.4, initial-scale=0.8,target-densitydpi=low-dpi" />
<link rel="stylesheet" th:href="@{/editormd/css/editormd.css}"/>
<link rel="shortcut icon" href="https://pandao.github.io/editor.md/favicon.ico" type="image/x-icon" />
head>
<body>
<div class="layui-fluid">
<div class="layui-row layui-col-space15">
<div class="layui-col-md12">
<form name="mdEditorForm" th:action="@{/article/add}" method="post">
<div>
标题:<input type="text" name="title">
div>
<div>
作者:<input type="text" name="author">
div>
<div id="article-content">
<textarea name="content" id="content" style="display:none;"> textarea>
div>
<input type="submit" value="提交">
form>
div>
div>
div>
body>
<script th:src="@{/editormd/js/jquery.min.js}">script>
<script th:src="@{/editormd/js/editormd.js}">script>
<script type="text/javascript">
var testEditor;
//window.onload = function(){ }
$(function() {
testEditor = editormd("article-content", {
placeholder:'本编辑器支持Markdown编辑,左边编写,右边预览',
width : "90%",
height : 400,
syncScrolling : "single",
path : "../editormd/lib/",
saveHTMLToTextarea : true, // 保存 HTML 到 Textarea
emoji: true,
theme: "default | dark",//工具栏主题
previewTheme: "default | dark",//预览主题
editorTheme: "default | dark",//编辑主题
tex : true, // 科学公式TeX语言支持,默认关闭
flowChart : true, // 流程图支持,默认关闭
sequenceDiagram : true, // 开启时序/序列图支持,默认关闭,
/*指定需要显示的功能按钮*/
toolbarIcons : function() {
//return editormd.toolbarModes.full;
//return editormd.toolbarModes.simple;
//return editormd.toolbarModes.mini;
return editormd.toolbarModes.me;
}
});
});
script>
html>
@Controller
@RequestMapping("/article")
public class ArticleController {
@Autowired
ArticleMapper articleMapper;
/**
* 进入添加文章
*
* @return
*/
@GetMapping("/toAdd")
public String add() {
return "article/add";
}
/**
* 添加文章
*
* @param article
* @return
*/
@PostMapping("/add")
public String add(Article article) {
articleMapper.addArticle(article);
return "redirect:/article/list";
}
/**
* 根据id查看文章
*
* @param id
* @param model
* @return
*/
@GetMapping("/{id}")
public String getArticle(@PathVariable("id") int id, Model model) {
Article article = articleMapper.getArticleById(id);
model.addAttribute("article", article);
return "article/article";
}
}
<script type="text/javascript">
var testEditor;
$(function() {
testEditor = editormd("article-content", {
//...
//图片上传
imageUpload : true,
imageFormats : ["jpg", "jpeg", "gif", "png", "bmp", "webp"],
imageUploadURL : "/article/file/upload",
onload : function() {
console.log('onload', this);
},
//...
});
});
script>
Controller 类中添加
/**
* 上传图片
*
* @param file
* @param request
* @return
* @throws IOException
*/
@RequestMapping("/file/upload")
@ResponseBody
public JSONObject fileUpload(@RequestParam(value = "editormd-image-file", required = true) MultipartFile file, HttpServletRequest request) throws IOException {
// =====上传路径保存设置======
// 获得SpringBoot当前项目的路径:System.getProperty("user.dir")
String path = System.getProperty("user.dir") + "\\upload\\";
// 按照年份、月份进行分类:
LocalDate date = LocalDate.now();
// 路径中不要加中文,否则在路径转码的情况下,回显会有问题
// String ym = date.getYear() + "\\" + date.getMonthValue() + "月";
String ym = date.getYear() + "\\" + date.getMonthValue();
path = path + ym;
File realPath = new File(path);
if (!realPath.exists()) {
// 这里有个坑;使用mkdirs,不是mkdir;因为mkdir只能创建一级目录,mkdirs可以创建多级目录
realPath.mkdirs();
}
// 上传文件地址
System.out.println("上传文件保存地址:" + realPath);
// 文件名
String filename = file.getOriginalFilename();
// 文件类型
String fileType = filename.substring(filename.lastIndexOf(".")).toLowerCase();
// 随机文件名:使用uuid;
filename = "img-" + UUID.randomUUID().toString().replaceAll("-", "") + fileType;
// 通过CommonsMultipartFile的方法直接写文件
file.transferTo(new File(realPath + "\\" + filename));
// 给editormd进行回调
JSONObject res = new JSONObject();
res.put("url", "\\upload\\" + ym + "\\" + filename);
res.put("success", 1);
res.put("message", "upload success!");
return res;
}
注意:
- 文件路径中
不要加中文
,否则在路径转码的情况下,回显会有问题- 创建路径时使用
mkdirs
,不是mkdir;因为mkdir只能创建一级目录,mkdirs可以创建多级目录
左侧编辑,右侧预览,实时显示图片,即回显
设置虚拟目录映射!在拓展的MvcConfig中进行配置即可!
访问的时候使用虚路径/upload,比如文件名为1.png,就直接/upload/1.png就ok了
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// 拦截请求格式:"/" 单斜杠,文件路径可以用 "\\" 双斜杠
registry.addResourceHandler("/upload/**")
.addResourceLocations("file:" + System.getProperty("user.dir") + "\\upload\\");
}
}
注意:
- 拦截请求格式:
/
单斜杠- 文件路径可以用
\\
双斜杠
使用本地表情
emoji
放至 editormd/plugins/emoji-dialog/
目录下// Emoji graphics files url path
editormd.emoji = {
//path : "https://www.webpagefx.com/tools/emoji-cheat-sheet/graphics/emojis/",
path : "../editormd/plugins/emoji-dialog/emoji/",
ext : ".png"
};
// Twitter Emoji (Twemoji) graphics files url path
// editormd.twemoji = {
// path : "http://twemoji.maxcdn.com/36x36/",
// ext : ".png"
// };
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<title th:text="${article.title}">title>
head>
<body>
<div>
<h2 th:text="${article.title}">h2>
作者:<span th:text="${article.author}">span>
<hr/>
<div id="doc-content">
<textarea placeholder="markdown" th:text="${article.content}">textarea>
div>
div>
<link rel="stylesheet" th:href="@{/editormd/css/editormd.preview.css}"/>
<script th:src="@{/editormd/js/jquery.min.js}">script>
<script th:src="@{/editormd/lib/marked.min.js}">script>
<script th:src="@{/editormd/lib/prettify.min.js}">script>
<script th:src="@{/editormd/lib/raphael.min.js}">script>
<script th:src="@{/editormd/lib/underscore.min.js}">script>
<script th:src="@{/editormd/lib/sequence-diagram.min.js}">script>
<script th:src="@{/editormd/lib/flowchart.min.js}">script>
<script th:src="@{/editormd/lib/jquery.flowchart.min.js}">script>
<script th:src="@{/editormd/js/editormd.js}">script>
<script type="text/javascript">
var testEditor;
$(function () {
testEditor = editormd.markdownToHTML("doc-content", {//注意:这里是上面DIV的id
htmlDecode: "style,script,iframe",
emoji: true,
taskList: true,
tocm: true,
tex: true, // 默认不解析
flowChart: true, // 默认不解析
sequenceDiagram: true, // 默认不解析
codeFold: true
});});
script>
body>
html>
/**
* 根据id查看文章
*
* @param id
* @param model
* @return
*/
@GetMapping("/{id}")
public String getArticle(@PathVariable("id") int id, Model model) {
Article article = articleMapper.getArticleById(id);
model.addAttribute("article", article);
return "article/article";
}