1. 程式人生 > 其它 >SpringBoot16:富文字編輯器

SpringBoot16:富文字編輯器

SpringBoot16:富文字編輯器

簡介

思考:我們平時在部落格園,或者CSDN等平臺進行寫作的時候,有同學思考過他們的編輯器是怎麼實現的嗎?

在部落格園後臺的選項設定中,可以看到一個文字編輯器的選項:

其實這個就是富文字編輯器,市面上有許多非常成熟的富文字編輯器,比如:

  • Editor.md——功能非常豐富的編輯器,左端編輯,右端預覽,非常方便,完全免費

    • 官網:https://pandao.github.io/editor.md/

  • wangEditor——基於javascript和css開發的 Web富文字編輯器, 輕量、簡潔、介面美觀、易用、開源免費。

    • 官網:http://www.wangeditor.com/

  • TinyMCE——TinyMCE是一個輕量級的基於瀏覽器的所見即所得編輯器,由JavaScript寫成。它對IE6+和Firefox1.5+都有著非常良好的支援。功能齊全,介面美觀,就是文件是英文的,對開發人員英文水平有一定要求。

    • 官網:https://www.tiny.cloud/docs/demo/full-featured/

    • 部落格園

  • 百度ueditor——UEditor是由百度web前端研發部開發所見即所得富文字web編輯器,具有輕量,功能齊全,可定製,注重使用者體驗等特點,開源基於MIT協議,允許自由使用和修改程式碼,缺點是已經沒有更新了

    • 官網:https://ueditor.baidu.com/website/onlinedemo.html

  • kindeditor——介面經典。

    • 官網:http://kindeditor.net/demo.php

  • Textbox——Textbox是一款極簡但功能強大的線上文字編輯器,支援桌面裝置和移動裝置。主要功能包含內建的影象處理和儲存、檔案拖放、拼寫檢查和自動更正。此外,該工具還實現了螢幕閱讀器等輔助技術,並符合WAI-ARIA可訪問性標準。

    • 官網:https://textbox.io/

  • CKEditor——國外的,介面美觀。

    • 官網:https://ckeditor.com/ckeditor-5/demo/

  • quill——功能強大,還可以編輯公式等

    • 官網:https://quilljs.com/

  • simditor——介面美觀,功能較全。

    • 官網:https://simditor.tower.im/

  • summernote——UI好看,精美

    • 官網:https://summernote.org/

  • jodit——功能齊全

    • 官網:https://xdsoft.net/jodit/

  • froala Editor——介面非常好看,功能非常強大,非常好用(非免費)

    • 官網:https://www.froala.com/wysiwyg-editor

總之,目前可用的富文字編輯器有很多......這只是其中的一部分

Editor.md

我這裡使用的就是Editor.md,作為一個資深碼農,Mardown必然是我們程式猿最喜歡的格式,看下面,就愛上了!

我們可以在官網下載它:https://pandao.github.io/editor.md/ , 得到它的壓縮包!

解壓以後,在examples目錄下面,可以看到他的很多案例使用!學習,其實就是看人家怎麼寫的,然後進行模仿就好了!

我們可以將整個解壓的檔案倒入我們的專案,將一些無用的測試和案例刪掉即可!

基礎工程搭建

資料庫設計

article:文章表

欄位備註
id int 文章的唯一ID
author varchar 作者
title varchar 標題
content longtext 文章的內容

建表SQL:

CREATETABLE`article` (
`id`int(10)NOTNULLAUTO_INCREMENT COMMENT'int文章的唯一ID',
`author`varchar(50)NOTNULLCOMMENT'作者',
`title`varchar(100)NOTNULLCOMMENT'標題',
`content`longtextNOTNULLCOMMENT'文章的內容',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

基礎專案搭建

1、建一個SpringBoot專案配置

spring:
datasource:
username:root
password:123456
#?serverTimezone=UTC解決時區的報錯
url:jdbc:mysql://localhost:3306/springboot?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
driver-class-name:com.mysql.cj.jdbc.Driver
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>

2、實體類:

//文章類
@Data
@NoArgsConstructor
@AllArgsConstructor
publicclassArticleimplementsSerializable{

privateintid;//文章的唯一ID
privateStringauthor;//作者名
privateStringtitle;//標題
privateStringcontent;//文章的內容

}

3、mapper介面:

@Mapper
@Repository
publicinterfaceArticleMapper{
//查詢所有的文章
List<Article>queryArticles();

//新增一個文章
intaddArticle(Articlearticle);

//根據文章id查詢文章
ArticlegetArticleById(intid);

//根據文章id刪除文章
intdeleteArticleById(intid);

}
<?xmlversion="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mappernamespace="com.kuang.mapper.ArticleMapper">

<selectid="queryArticles"resultType="Article">
select * from article
</select>

<selectid="getArticleById"resultType="Article">
select * from article where id = #{id}
</select>

<insertid="addArticle"parameterType="Article">
insert into article (author,title,content) values (#{author},#{title},#{content});
</insert>

<deleteid="deleteArticleById"parameterType="int">
delete from article where id = #{id}
</delete>

</mapper>

既然已經提供了 myBatis 的對映配置檔案,自然要告訴 spring boot 這些檔案的位置

mybatis:
mapper-locations:classpath:com/kuang/mapper/*.xml
type-aliases-package:com.kuang.pojo

編寫一個Controller測試下,是否ok;

文章編輯整合(重點)

1、匯入 editor.md 資源 ,刪除多餘檔案

2、編輯文章頁面 editor.html、需要引入 jQuery;

<!DOCTYPE html>
<htmlclass="x-admin-sm"lang="zh"xmlns:th="http://www.thymeleaf.org">

<head>
<metacharset="UTF-8">
<title>秦疆'Blog</title>
<metaname="renderer"content="webkit">
<metahttp-equiv="X-UA-Compatible"content="IE=edge,chrome=1">
<metaname="viewport"content="width=device-width,user-scalable=yes, minimum-scale=0.4, initial-scale=0.8,target-densitydpi=low-dpi"/>
<!--Editor.md-->
<linkrel="stylesheet"th:href="@{/editormd/css/editormd.css}"/>
<linkrel="shortcut icon"href="https://pandao.github.io/editor.md/favicon.ico"type="image/x-icon"/>
</head>

<body>

<divclass="layui-fluid">
<divclass="layui-row layui-col-space15">
<divclass="layui-col-md12">
<!--部落格表單-->
<formname="mdEditorForm">
<div>
標題:<inputtype="text"name="title">
</div>
<div>
作者:<inputtype="text"name="author">
</div>
<divid="article-content">
<textareaname="content"id="content"style="display:none;"></textarea>
</div>
</form>

</div>
</div>
</div>
</body>

<!--editormd-->
<scriptth:src="@{/editormd/lib/jquery.min.js}"></script>
<scriptth:src="@{/editormd/editormd.js}"></script>

<scripttype="text/javascript">
vartestEditor;

//window.onload = function(){ }
$(function() {
testEditor=editormd("article-content", {
width:"95%",
height:400,
syncScrolling:"single",
path:"../editormd/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='/';
},
}
});
});
</script>

</html>

3、編寫Controller,進行跳轉,以及儲存文章

@Controller
@RequestMapping("/article")
publicclassArticleController{

@GetMapping("/toEditor")
publicStringtoEditor(){
return"editor";
}

@PostMapping("/addArticle")
publicStringaddArticle(Articlearticle){
articleMapper.addArticle(article);
return"editor";
}

}

圖片上傳問題

1、前端js中新增配置

//圖片上傳
imageUpload:true,
imageFormats: ["jpg","jpeg","gif","png","bmp","webp"],
imageUploadURL:"/article/file/upload",// //這個是上傳圖片時的訪問地址

2、後端請求,接收儲存這個圖片, 需要匯入 FastJson 的依賴!

//部落格圖片上傳問題
@RequestMapping("/file/upload")
@ResponseBody
publicJSONObjectfileUpload(@RequestParam(value="editormd-image-file",required=true)MultipartFilefile,HttpServletRequestrequest)throwsIOException{
//上傳路徑儲存設定

//獲得SpringBoot當前專案的路徑:System.getProperty("user.dir")
Stringpath=System.getProperty("user.dir")+"/upload/";

//按照月份進行分類:
Calendarinstance=Calendar.getInstance();
Stringmonth=(instance.get(Calendar.MONTH)+1)+"月";
path=path+month;

FilerealPath=newFile(path);
if(!realPath.exists()){
realPath.mkdir();
}

//上傳檔案地址
System.out.println("上傳檔案儲存地址:"+realPath);

//解決檔名字問題:我們使用uuid;
Stringfilename="ks-"+UUID.randomUUID().toString().replaceAll("-","");
//通過CommonsMultipartFile的方法直接寫檔案(注意這個時候)
file.transferTo(newFile(realPath+"/"+filename));

//給editormd進行回撥
JSONObjectres=newJSONObject();
res.put("url","/upload/"+month+"/"+filename);
res.put("success",1);
res.put("message","upload success!");

returnres;
}

3、解決檔案回顯顯示的問題,設定虛擬目錄對映!在我們自己拓展的MvcConfig中進行配置即可!

@Configuration
publicclassMyMvcConfigimplementsWebMvcConfigurer{

// 檔案儲存在真實目錄/upload/下,
// 訪問的時候使用虛路徑/upload,比如檔名為1.png,就直接/upload/1.png就ok了。
@Override
publicvoidaddResourceHandlers(ResourceHandlerRegistryregistry) {
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}")
publicStringshow(@PathVariable("id")intid,Modelmodel){
Articlearticle=articleMapper.getArticleById(id);
model.addAttribute("article",article);
return"article";
}

2、編寫頁面 article.html

<!DOCTYPE html>
<htmllang="en"xmlns:th="http://www.thymeleaf.org">
<head>
<metacharset="UTF-8">
<metaname="viewport"content="width=device-width, initial-scale=1, maximum-scale=1">
<titleth:text="${article.title}"></title>
</head>
<body>

<div>
<!--文章頭部資訊:標題,作者,最後更新日期,導航-->
<h2style="margin: auto 0"th:text="${article.title}"></h2>
作者:<spanstyle="float: left"th:text="${article.author}"></span>
<!--文章主體內容-->
<divid="doc-content">
<textareastyle="display:none;"placeholder="markdown"th:text="${article.content}"></textarea>
</div>

</div>

<linkrel="stylesheet"th:href="@{/editormd/css/editormd.preview.css}"/>
<scriptth:src="@{/editormd/lib/jquery.min.js}"></script>
<scriptth:src="@{/editormd/lib/marked.min.js}"></script>
<scriptth:src="@{/editormd/lib/prettify.min.js}"></script>
<scriptth:src="@{/editormd/lib/raphael.min.js}"></script>
<scriptth:src="@{/editormd/lib/underscore.min.js}"></script>
<scriptth:src="@{/editormd/lib/sequence-diagram.min.js}"></script>
<scriptth:src="@{/editormd/lib/flowchart.min.js}"></script>
<scriptth:src="@{/editormd/lib/jquery.flowchart.min.js}"></script>
<scriptth:src="@{/editormd/editormd.js}"></script>

<scripttype="text/javascript">
vartestEditor;
$(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>

重啟專案,訪問進行測試!大功告成!

小結:

有了富文字編輯器,我們網站的功能就會又多一項,大家到了這裡完全可以有時間寫一個屬於自己的部落格網站了,根據所學的知識是完全沒有任何問題的!

end