1.效果展示
數據庫數據:
看完效果,如果能滿足我們需求,那我們就進行下去!
富文本編輯器的資源文件夾:鏈接:https://pan.baidu.com/s/16hJGPNOso6My7XwivZn_Zw 提取碼:a7lt
2.springboot框架創建各種包
1.pom.xml 依賴
<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.1.4</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</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>
2.啟動類同級目錄下創建config、controller、entity、mapper、service等包。如圖:
3.application.yml 和application-dev.yml配置文件
spring:
profiles:
active: dev
server:
port: 8080
spring:
datasource:
username: root
password: root
url: jdbc:mysql://localhost:3306/db2019?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
mapper-locations: classpath:mapping/*Mapping.xml
type-aliases-package: com.dzb.mybatiseditor.entity
#showSql
logging:
level:
com:
dzb:
mybatiseditor:
mapper: DEBUG
4. resources 文件夾下創建mapping 文件夾,並且將富文本編輯器文件夾editormd拷貝到resources下。
5.配置靜態資源映射類和Article各層包類
config 文件夾 創建 WebMvcConfig配置類,目的:靜態資源允許訪問。
/**
* 配置靜態資源映射
**/
@Component
public class WebMvcConfig implements WebMvcConfigurer {
/**
* 添加靜態資源文件,外部可以直接訪問地址
* @param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
registry.addResourceHandler("/editormd/**").addResourceLocations("classpath:/editormd/");
registry.addResourceHandler("/upload/**").addResourceLocations("file:"+System.getProperty("user.dir")+"/upload/");
//此處還可繼續增加目錄。。。。
}
}
entity 包下 創建 Article實體類
public class Article implements Serializable {
private Integer id ; // 文章ID
private String author ; // 文章的作者
private String title ; // 標題
private String content ; // 文章內容
public Article() {
}
public Article(String author, String title, String content) {
this.author = author;
this.title = title;
this.content = content;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
@Override
public String toString() {
return "Article{" +
"id=" + id +
", author='" + author + '\'' +
", title='" + title + '\'' +
", content='" + content + '\'' +
'}';
}
}
controller 包下創建 ArticleController類,service包下創建ArticleService接口,service.impl包下創建ArticleServiceImpl類
@Controller
@RequestMapping("/article")
public class ArticleController {
}
@Service
public class ArticleServiceImpl implements ArticleService {
}
啟動類添加 @MapperScan("com.dzb.mybatiseditor.mapper") 注解
3、展示頁顯示詳細
ArticleController 類創建article方法,由於Thymeleaf 的支持,返回article.html靜態頁面。(templates文件夾創建article.html頁面)
@RequestMapping(value = {"","/"})
public String article(){
return "article";
}
article.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">
<meta name="viewport"
content="width=device-width,user-scalable=yes, minimum-scale=0.4, initial-scale=0.8,target-densitydpi=low-dpi"/>
<!--Editor.md-->
<link rel="stylesheet" th:href="@{/editormd/css/editormd.css}"/>
<link rel="stylesheet" th:href="@{/static/css/bootstrap.min.css}"/>
<link rel="shortcut icon" href="https://pandao.github.io/editor.md/favicon.ico" type="image/x-icon"/>
</head>
<!--寫博客頁面-->
<body>
<h1 style="text-align: center">EditorMd 富文本編輯器初體驗</h1>
<div class="panel panel-default" style="width: 90%;margin: auto;">
<div class="panel-body">
<!--博客表單-->
<form name="mdEditorForm">
<!-- 文章的標題 -->
<div class="input-group input-group-lg">
<span class="input-group-addon" id="sizing-addon1">標題</span>
<input type="text" class="form-control" placeholder="請輸入標題" aria-describedby="sizing-addon1" name="title" autocomplete="off" required>
</div>
<br>
<!-- 文章的作者 -->
<div class="input-group input-group-lg ">
<span class="input-group-addon" id="sizing-addon2">作者</span>
<input type="text" class="form-control" placeholder="請輸入作者" aria-describedby="sizing-addon2" name="author" autocomplete="off" required>
</div>
<br>
<!-- 文章的主體內容 textarea -->
<!--富文本編輯器以 id="article-content" 為定位點 -->
<div id="article-content">
<textarea name="content" id="content" style="display:none;"> </textarea>
</div>
</form>
</div>
</div>
</body>
<!--editormd-->
<script src="/editormd/jquery-3.3.1.min.js"></script>
<script src="/editormd/editormd.js"></script>
<script type="text/javascript">
var testEditor;
$(function () {
//這是一個最簡單的Editormd配置,往后我們要修改Editormd的
//功能或者樣式,就改這里的配置就可以了
testEditor = editormd("article-content", {
width: "100%", // 設置富文本編輯框的寬度
height: 500,
syncScrolling: "single",
path: "/editormd/lib/",
// 自定義的增強配置!
saveHTMLToTextarea: true, // 保存 HTML 到 Textarea
htmlDecode: "style,script,iframe",
emoji: true, // 開啟表情的功能! 圖片的本地配置!
taskList: true,
theme: "light",//工具欄主題
// previewTheme: "dark",//預覽主題
// editorTheme: "pastel-on-dark",//編輯主題
// markdown的配置!
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"]
},
// 這里的自定義功能就好比,Vue 組件
/*自定義功能按鈕,下面我自定義了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>
插入圖片
我們需要注意的地方:
添加editormd.css
<link rel="stylesheet" th:href="@{/editormd/css/editormd.css}"/>
富文本編輯器是以id = "article-content"為定位點,需要更改時,要更改此處的id坐標
當我們上傳圖片時,上傳圖片的接口路徑為:
ArticleController類新建文件上傳路徑方法。圖片上傳到src同級目錄upload文件夾下。
完整代碼
@Autowired
private ArticleService articleService;
// MarkDown博客圖片上傳問題
@RequestMapping(value = "/file/upload",method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@ResponseBody
public HashMap 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:" + path);
//按照月份進行分類:
Calendar instance = Calendar.getInstance();
String month = (instance.get(Calendar.MONTH) + 1)+"月";
path = path +month;
File realPath = new File(path);
if (!realPath.exists()){
realPath.mkdirs();
}
//上傳文件地址
System.out.println("上傳文件保存地址:"+realPath);
//解決文件名字問題:我們使用uuid;
String filename = "ks-"+ UUID.randomUUID().toString().replaceAll("-", "")+".jpg";
//通過CommonsMultipartFile的方法直接寫文件(注意這個時候)
file.transferTo(new File(realPath +"/"+ filename));
//給editormd進行回調
HashMap res = new HashMap();
res.put("url","/upload/"+month+"/"+ filename);
res.put("success", 1);
res.put("message", "upload success!");
System.out.println(res);
return res;
}
富文本編輯器的發布和返回首頁按鈕可以自定義:
4、數據提交至數據庫
我們可以在上圖中看到 當我們點擊發布時,數據提交至服務器的路徑 為: /article/add/Article ,當我們需要改為自己的路徑時,可以在此更改。
我們可以看到 : 提交數據時,是 mdEditorForm.submit(),這就意味着,我們需要在form標簽添加 name = mdEditorForm,這是需要注意的一點。而且 標題和作者的input輸入框也需要name屬性。
ArticleController 類添加路徑方法addArticle。 添加成功后將文章數據隨着返回到前端success.html頁面(templates文件夾下創建success.html頁面)
@RequestMapping("/addArticle")
public String addArticle(Article article, Model model){
if(article == null){
throw new IllegalArgumentException("參數不能為空");
}
int result = articleService.addArticle(article);
System.out.println(article);
System.out.println(result);
if(result == 1){
model.addAttribute("article",article);
return "success";
}
return "success";
}
service包下UserService類:
public interface UserService {
public User Sel(int id);
}
service.impl包下ArticleServiceImpl類
@Service
public class ArticleServiceImpl implements ArticleService {
@Autowired
private ArticleMapper articleMapper;
@Override
public int addArticle(Article article) {
return articleMapper.addArticle(article);
}
}
mapper包下ArticleMapper 類
@Repository
public interface ArticleMapper {
int addArticle(Article article);
}
resources/mapping 文件夾下新建 ArticleMapping.xml 配置文件
<?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.dzb.mybatiseditor.mapper.ArticleMapper">
<resultMap id="BaseResultMap" type="com.dzb.mybatiseditor.entity.Article">
<result column="id" jdbcType="INTEGER" property="id" />
<result column="author" jdbcType="VARCHAR" property="author" />
<result column="title" jdbcType="VARCHAR" property="title" />
<result column="content" jdbcType="VARCHAR" property="content" />
</resultMap>
<insert id="addArticle" parameterType="com.dzb.mybatiseditor.entity.Article" useGeneratedKeys="true" keyProperty="id">
insert into article (author,title,content) value (#{author},#{title},#{content})
</insert>
</mapper>
注:static靜態文件自取 。(在完整代碼中)
數據庫表:
CREATE TABLE `article` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`author` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`title` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '文章標題',
`content` text CHARACTER SET utf8 COLLATE utf8_general_ci NULL COMMENT '文章內容',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 13 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
5.數據回顯
1.添加成功后返回success.html頁面 的同時,攜帶着article參數。
要想讓markdown語法的字符串用Markdown排版顯示,需要使用 [[ ]] 這種表示形式
success.html完整代碼 :
<!DOCTYPE html>
<html class="x-admin-sm" lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>添加成功</h1>
<hr>
<!--帖子內容-->
<div class="m-text ui attached padded segment">
<div class="typo typo-selection">
<div id="test-editormd-view">
<textarea id="append-test" style="display:none;">[[${article.content}]]</textarea>
</div>
</div>
</div>
<!--editormd-->
<script src="/editormd/jquery-3.3.1.min.js"></script>
<!--editormd-->
<script src="/editormd/lib/marked.min.js" ></script>
<script src="/editormd/lib/prettify.min.js" ></script>
<script src="/editormd/lib/raphael.min.js"></script>
<script src="/editormd/lib/underscore.min.js" ></script>
<script src="/editormd/lib/sequence-diagram.min.js" ></script>
<script src="/editormd/lib/flowchart.min.js" ></script>
<script src="/editormd/lib/jquery.flowchart.min.js" ></script>
<script src="/editormd/editormd.js"></script>
<script type="text/javascript">
/*editormd*/
$(function () {
editormd.markdownToHTML("test-editormd-view", {
htmlDecode : "style,script,iframe", // you can filter tags decode
emoji : true,
taskList : true,
tex : true, // 默認不解析
flowChart : true, // 默認不解析
sequenceDiagram : true, // 默認不解析
});
})
</script>
</body>
</html>
啟動
訪問地址 : http://localhost:8080/article
數據提交 :點擊 發布按鈕
提交后數據回顯在網頁上 : http://localhost:8080/article/addArticle (提交后自動跳轉)
完整代碼 地址:鏈接:https://pan.baidu.com/s/1CWXofs56TqsmYjnje9IfqQ 提取碼:nnqh