EditorMd 富文本编辑器使用(springboot版)

1.效果展示

editor-show

editor-show2

数据库数据:

editor-show-sql

看完效果,如果能满足我们需求,那我们就进行下去!

富文本编辑器的资源文件夹:链接: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等包。如图:

editor-mybatis

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下。

editor-mybatis2

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") 注解

editor-mybatis10

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>

插入图片

editor-mybatis7

我们需要注意的地方:

添加editormd.css

 <link rel="stylesheet" th:href="@{/editormd/css/editormd.css}"/>

富文本编辑器是以id = "article-content"为定位点,需要更改时,要更改此处的id坐标

editor-mybatis3

当我们上传图片时,上传图片的接口路径为:

editor-mybatis5

ArticleController类新建文件上传路径方法。图片上传到src同级目录upload文件夹下。

editor-mybatis6

完整代码

@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;
}

富文本编辑器的发布和返回首页按钮可以自定义:

editor-mybatis8

4、数据提交至数据库

我们可以在上图中看到 当我们点击发布时,数据提交至服务器的路径 为: /article/add/Article ,当我们需要改为自己的路径时,可以在此更改。

我们可以看到 : 提交数据时,是 mdEditorForm.submit(),这就意味着,我们需要在form标签添加 name = mdEditorForm,这是需要注意的一点。而且 标题和作者的input输入框也需要name属性。

editor-mybatis9

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参数。

editor-mybatis11

要想让markdown语法的字符串用Markdown排版显示,需要使用 [[ ]] 这种表示形式

editor-success

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

posted @ 2021-02-27 23:24  duanxiaobiao  阅读(1781)  评论(0编辑  收藏  举报