富文本编辑器Editor.md入门
Editor.md入門
一、富文本編輯器介紹
什么是富文本編輯器?
我們平時在博客園,或者CSDN等平臺進行寫作的時候,他們的編輯器就是富文本編輯器。
其實這個就是富文本編輯器,市面上有許多非常成熟的富文本編輯器。這個文章有很多介紹https://blog.csdn.net/davidhzq/article/details/100815332想了解的小伙伴可以看一下這里就不一一列舉了。
下面進入我們的主題Editor.md
二、Editor.md介紹
Editor.md——功能非常豐富的編輯器,左端編輯,右端預(yù)覽,非常方便,完全免費
官網(wǎng):https://pandao.github.io/editor.md/
我們在官網(wǎng)下載它的壓縮包,解壓以后,在examples目錄下面,可以看到他的很多案例使用。
然后我們刪除多余的文件,把有用的導(dǎo)入項目中。
將多余的文件刪除,把文件名改為md(這個隨便什么都可以),導(dǎo)入項目中
三、搭建springboot項目
1、數(shù)據(jù)庫設(shè)計
article:文章表
2.創(chuàng)建項目導(dǎo)入web模塊
3、導(dǎo)入相關(guān)依賴
<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驅(qū)動--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.49</version></dependency><!--數(shù)據(jù)源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配置文件
這里做了三件事 連接數(shù)據(jù)庫、設(shè)置數(shù)據(jù)源、整合mybatis
spring:datasource:username: rootpassword: x5#?serverTimezone=UTC解決時區(qū)的報錯url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8driver-class-name: com.mysql.jdbc.Drivertype: com.alibaba.druid.pool.DruidDataSource#Spring Boot 默認是不注入這些屬性值的,需要自己綁定#druid 數(shù)據(jù)源專有配置initialSize: 5minIdle: 5maxActive: 20maxWait: 60000timeBetweenEvictionRunsMillis: 60000minEvictableIdleTimeMillis: 300000validationQuery: SELECT 1 FROM DUALtestWhileIdle: truetestOnBorrow: falsetestOnReturn: falsepoolPreparedStatements: true#配置監(jiān)控統(tǒng)計攔截的filters,stat:監(jiān)控統(tǒng)計、log4j:日志記錄、wall:防御sql注入#如果允許時報錯 java.lang.ClassNotFoundException: org.apache.log4j.Priority#則導(dǎo)入 log4j 依賴即可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4jfilters: stat,wall,log4jmaxPoolPreparedStatementPerConnectionSize: 20useGlobalDataSourceStat: trueconnectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500 #整合Mybatis mybatis:type-aliases-package: com.zhao.pojomapper-locations: classpath:mapper/*.xml5、實體類
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; //文章的唯一IDprivate String author; //作者名private String title; //標題private String content; //文章的內(nèi)容}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);//根據(jù)文章id查詢文章Article getArticleById(int id);//根據(jù)文章id刪除文章int deleteArticleById(int id);}在mapper下創(chuàng)建,因為上面配置的是這個路徑
測試一樣搭建的環(huán)境是否有問題,沒有問題我們就開始學(xué)習(xí)
四、文章編輯整合(重點)
1、導(dǎo)入 editor.md 資源
主要導(dǎo)入紅色框里的
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 到 Textareaemoji: true,theme: "dark",//工具欄主題previewTheme: "dark",//預(yù)覽主題editorTheme: "pastel-on-dark",//編輯主題tex : true, // 開啟科學(xué)公式TeX語言支持,默認關(guān)閉flowChart : true, // 開啟流程圖支持,默認關(guān)閉sequenceDiagram : true, // 開啟時序/序列圖支持,默認關(guān)閉,//圖片上傳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個,一個是發(fā)布,一個是返回首頁*/toolbarIconTexts : {releaseIcon : "<span bgcolor=\"gray\">發(fā)布</span>",index : "<span bgcolor=\"red\">返回首頁</span>",},/*給自定義按鈕指定回調(diào)函數(shù)*/toolbarHandlers:{releaseIcon : function(cm, icon, cursor, selection) {//表單提交mdEditorForm.method = "post";mdEditorForm.action = "/article/addArticle";//提交至服務(wù)器的路徑mdEditorForm.submit();},index : function(){window.location.href = '/article/toEditor';//刷新當(dāng)前頁面},}});}); </script></html>3、編寫Controller,進行跳轉(zhuǎn),以及保存文章
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 {@AutowiredArticleMapper articleMapper;@GetMapping("/toEditor")public String toEditor() {return "editor";}@PostMapping("/addArticle")public String addArticle(Article article) {articleMapper.addArticle(article);return "editor";} }到這里我們就可以上傳文章了
上傳成功,數(shù)據(jù)庫如下
五、圖片上傳問題
1、頁面代碼
在頁面中已經(jīng)寫了圖片上傳的設(shè)置,代碼如下
//圖片上傳 imageUpload : true, imageFormats : ["jpg", "jpeg", "gif", "png", "bmp", "webp"], imageUploadURL : "/article/file/upload", // //這個是上傳圖片時的訪問地址2、controller層添加圖片上傳方法
//博客圖片上傳問題@RequestMapping("/file/upload")@ResponseBodypublic JSONObject fileUpload(@RequestParam(value = "editormd-image-file", required = true) MultipartFile file, HttpServletRequest request) throws IOException {//上傳路徑保存設(shè)置//獲得SpringBoot當(dāng)前項目的路徑: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進行回調(diào)JSONObject res = new JSONObject();res.put("url","/upload/"+month+"/"+ filename);res.put("success", 1);res.put("message", "upload success!");return res;}3、解決文件回顯顯示的問題
設(shè)置虛擬目錄映射!在我們自己拓展的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了。@Overridepublic void addResourceHandlers(ResourceHandlerRegistry registry) {registry.addResourceHandler("/upload/**").addResourceLocations("file:"+System.getProperty("user.dir")+"/upload/");}}這里運行如果報錯可能是沒有文件夾,手動創(chuàng)建就行。
六、表情包問題
自己手動下載,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><!--文章頭部信息:標題,作者,最后更新日期,導(dǎo)航--><h2 style="margin: auto 0" th:text="${article.title}"></h2>作者:<span style="" th:text="${article.author}"></span><!--文章主體內(nèi)容--><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的idhtmlDecode: "style,script,iframe",emoji: true,taskList: true,tocm: true,tex: true, // 默認不解析flowChart: true, // 默認不解析sequenceDiagram: true, // 默認不解析codeFold: true});}); </script> </body> </html>現(xiàn)在我們就可從新啟動項目進行測試了
八、整體測試
1、圖片上傳
2.編輯文章,顯示圖片
3、文章顯示
總結(jié)
以上是生活随笔為你收集整理的富文本编辑器Editor.md入门的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SM3算法设计原理
- 下一篇: UR+RealSense手眼标定(eye