富文本编辑器Editor.md入门
Editor.md入门一、富文本编辑器介绍什么是富文本编辑器?我们平时在博客园,或者CSDN等平台进行写作的时候,他们的编辑器就是富文本编辑器。其实这个就是富文本编辑器,市面上有许多非常成熟的富文本编辑器。这个文章有很多介绍https://blog.csdn.net/davidhzq/article/details/100815332想了解的小伙伴可以看一下这里就不一一列举了。下面进入我们的主题E
Editor.md入门
一、富文本编辑器介绍
什么是富文本编辑器?
我们平时在博客园,或者CSDN等平台进行写作的时候,他们的编辑器就是富文本编辑器。
其实这个就是富文本编辑器,市面上有许多非常成熟的富文本编辑器。这个文章有很多介绍https://blog.csdn.net/davidhzq/article/details/100815332想了解的小伙伴可以看一下这里就不一一列举了。
下面进入我们的主题Editor.md
二、Editor.md介绍
Editor.md——功能非常丰富的编辑器,左端编辑,右端预览,非常方便,完全免费
官网:https://pandao.github.io/editor.md/
我们在官网下载它的压缩包,解压以后,在examples目录下面,可以看到他的很多案例使用。
然后我们删除多余的文件,把有用的导入项目中。
将多余的文件删除,把文件名改为md(这个随便什么都可以),导入项目中
三、搭建springboot项目
1、数据库设计
article:文章表
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
2.创建项目导入web模块
3、导入相关依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.66</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.10</version>
</dependency>
<!--MySQL驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.49</version>
</dependency>
<!--数据源druid-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.12</version>
</dependency>
<!---->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
<!--thymeleaf xmlns:th="http://www.thymeleaf.org-->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
4、编写application.yml配置文件
这里做了三件事 连接数据库、设置数据源、整合mybatis
spring:
datasource:
username: root
password: x5
#?serverTimezone=UTC解决时区的报错
url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
driver-class-name: com.mysql.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
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
#配置监控统计拦截的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
#整合Mybatis
mybatis:
type-aliases-package: com.zhao.pojo
mapper-locations: classpath:mapper/*.xml
5、实体类
package com.zhao.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
//文章类
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Article implements Serializable {
private int id; //文章的唯一ID
private String author; //作者名
private String title; //标题
private String content; //文章的内容
}
6、mapper接口:
package com.zhao.mapper;
import com.zhao.pojo.Article;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import java.util.List;
@Mapper
@Repository
public interface ArticleMapper {
//查询所有的文章
List<Article> queryArticles();
//新增一个文章
int addArticle(Article article);
//根据文章id查询文章
Article getArticleById(int id);
//根据文章id删除文章
int deleteArticleById(int id);
}
在mapper下创建,因为上面配置的是这个路径
<?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.zhao.mapper.ArticleMapper">
<select id="queryArticles" resultType="Article">
select * from article
</select>
<select id="getArticleById" resultType="Article">
select * from article where id = #{id}
</select>
<insert id="addArticle" parameterType="Article">
insert into article (author,title,content) values (#{author},#{title},#{content});
</insert>
<delete id="deleteArticleById" parameterType="int">
delete from article where id = #{id}
</delete>
</mapper>
测试一样搭建的环境是否有问题,没有问题我们就开始学习
四、文章编辑整合(重点)
1、导入 editor.md 资源
主要导入红色框里的
2.editor.html编辑页面
<!DOCTYPE html>
<html class="x-admin-sm" lang="zh" 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">
<!--Editor.md-->
<link rel="stylesheet" th:href="@{/md/css/editormd.css}"/>
<link rel="stylesheet" th:href="@{/layui/css/layui.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">
<div>
标题:<input class="layui-input" type="text" name="title">
</div>
<div>
作者:<input class="layui-input" type="text" name="author">
</div>
<div id="article-content">
<textarea name="content" id="content" style=""> </textarea>
</div>
</form>
</div>
</div>
</div>
</body>
<!--editormd-->
<script th:src="@{/js/jquery-2.1.0.js}"></script>
<script th:src="@{/md/editormd.js}"></script>
<script type="text/javascript">
var testEditor;
//window.onload = function(){ }
$(function() {
testEditor = editormd("article-content", {
width : "95%",
height : "1000px",
syncScrolling : "single",
path : "../md/lib/", //使用自己的路径
saveHTMLToTextarea : true, // 保存 HTML 到 Textarea
emoji: true,
theme: "dark",//工具栏主题
previewTheme: "dark",//预览主题
editorTheme: "pastel-on-dark",//编辑主题
tex : true, // 开启科学公式TeX语言支持,默认关闭
flowChart : true, // 开启流程图支持,默认关闭
sequenceDiagram : true, // 开启时序/序列图支持,默认关闭,
//图片上传
imageUpload : true,
imageFormats : ["jpg", "jpeg", "gif", "png", "bmp", "webp"],
imageUploadURL : "/article/file/upload", //图片上传路径
onload : function() {
console.log('onload', this);
},
/*指定需要显示的功能按钮*/
toolbarIcons : function() {
return ["undo","redo","|",
"bold","del","italic","quote","ucwords","uppercase","lowercase","|",
"h1","h2","h3","h4","h5","h6","|",
"list-ul","list-ol","hr","|",
"link","reference-link","image","code","preformatted-text",
"code-block","table","datetime","emoji","html-entities","pagebreak","|",
"goto-line","watch","preview","fullscreen","clear","search","|",
"help","info","releaseIcon", "index"]
},
/*自定义功能按钮,下面我自定义了2个,一个是发布,一个是返回首页*/
toolbarIconTexts : {
releaseIcon : "<span bgcolor=\"gray\">发布</span>",
index : "<span bgcolor=\"red\">返回首页</span>",
},
/*给自定义按钮指定回调函数*/
toolbarHandlers:{
releaseIcon : function(cm, icon, cursor, selection) {
//表单提交
mdEditorForm.method = "post";
mdEditorForm.action = "/article/addArticle";//提交至服务器的路径
mdEditorForm.submit();
},
index : function(){
window.location.href = '/article/toEditor';//刷新当前页面
},
}
});
});
</script>
</html>
3、编写Controller,进行跳转,以及保存文章
package com.zhao.controller;
import com.zhao.mapper.ArticleMapper;
import com.zhao.pojo.Article;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
@Controller
@RequestMapping("/article")
public class ArticleController {
@Autowired
ArticleMapper articleMapper;
@GetMapping("/toEditor")
public String toEditor() {
return "editor";
}
@PostMapping("/addArticle")
public String addArticle(Article article) {
articleMapper.addArticle(article);
return "editor";
}
}
到这里我们就可以上传文章了
上传成功,数据库如下
五、图片上传问题
1、页面代码
在页面中已经写了图片上传的设置,代码如下
//图片上传
imageUpload : true,
imageFormats : ["jpg", "jpeg", "gif", "png", "bmp", "webp"],
imageUploadURL : "/article/file/upload", // //这个是上传图片时的访问地址
2、controller层添加图片上传方法
//博客图片上传问题
@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/";
System.out.println(path);
//按照月份进行分类:
Calendar instance = Calendar.getInstance();
String month = (instance.get(Calendar.MONTH) + 1)+"月";
path = path+month;
File realPath = new File(path);
if (!realPath.exists()){
realPath.mkdir();
}
//上传文件地址
System.out.println("上传文件保存地址:"+realPath);
//解决文件名字问题:我们使用uuid;
String filename = "ks-"+ UUID.randomUUID().toString().replaceAll("-", "");
//通过CommonsMultipartFile的方法直接写文件(注意这个时候)
file.transferTo(new File(realPath +"/"+ filename));
//给editormd进行回调
JSONObject res = new JSONObject();
res.put("url","/upload/"+month+"/"+ filename);
res.put("success", 1);
res.put("message", "upload success!");
return res;
}
3、解决文件回显显示的问题
设置虚拟目录映射!在我们自己拓展的MvcConfig中进行配置即可!
package com.zhao.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
// 文件保存在真实目录/upload/下,
// 访问的时候使用虚路径/upload,比如文件名为1.png,就直接/upload/1.png就ok了。
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/upload/**")
.addResourceLocations("file:"+System.getProperty("user.dir")+"/upload/");
}
}
这里运行如果报错可能是没有文件夹,手动创建就行。
六、表情包问题
自己手动下载,emoji 表情包,放到图片路径下:
修改editormd.js文件
// Emoji graphics files url path
editormd.emoji = {
path : "../editormd/plugins/emoji-dialog/emoji/",
ext : ".png"
};
七、文章展示
1、Controller 中增加方法
@GetMapping("/{id}")
public String show(@PathVariable("id") int id,Model model){
Article article = articleMapper.getArticleById(id);
model.addAttribute("article",article);
return "article";
}
2、编写页面 article.html
<!DOCTYPE html>
<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 style="margin: auto 0" th:text="${article.title}"></h2>
作者:<span style="" th:text="${article.author}"></span>
<!--文章主体内容-->
<div id="doc-content">
<textarea style="" placeholder="markdown" th:text="${article.content}"></textarea>
</div>
</div>
<link rel="stylesheet" th:href="@{/md/css/editormd.preview.css}" />
<script th:src="@{/js/jquery-2.1.0.js}"></script>
<script th:src="@{/md/lib/marked.min.js}"></script>
<script th:src="@{/md/lib/prettify.min.js}"></script>
<script th:src="@{/md/lib/raphael.min.js}"></script>
<script th:src="@{/md/lib/underscore.min.js}"></script>
<script th:src="@{/md/lib/sequence-diagram.min.js}"></script>
<script th:src="@{/md/lib/flowchart.min.js}"></script>
<script th:src="@{/md/lib/jquery.flowchart.min.js}"></script>
<script th:src="@{/md/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>
现在我们就可从新启动项目进行测试了
八、整体测试
1、图片上传
2.编辑文章,显示图片
3、文章显示
更多推荐
所有评论(0)