springboot2.1集成Editor.md

- 1.Editor.md介绍

先看一下效果图,是你想要的结果继续往下看
springboot2.1集成Editor.md_第1张图片
官网介绍

  • 支持“标准”Markdown / CommonMark和Github风格的语法,也可变身为代码编辑器;
  • 支持实时预览、图片(跨域)上传、预格式文本/代码/表格插入、代码折叠、搜索替换、只读模式、自定义样式主题和多语言语法高亮等功能;
  • 支持ToC(Table of Contents)、Emoji表情、Task lists、@链接等Markdown扩展语法;
  • 支持TeX科学公式(基于KaTeX)、流程图 Flowchart 和 时序图 Sequence Diagram;
  • 支持识别和解析HTML标签,并且支持自定义过滤标签解析,具有可靠的安全性和几乎无限的扩展性;
  • 支持 AMD / CMD 模块化加载(支持 Require.js & Sea.js),并且支持自定义扩展插件;
  • 兼容主流的浏览器(IE8+)和Zepto.js,且支持iPad等平板设备;
  • 支持自定义主题样式;

2.下载

官网 http://editor.md.ipandao.com/
github地址 https://github.com/pandao/editor.md.git

  • 下载官网的zip,解压

3.开始

创建springboot项目,添加依赖

 <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-thymeleafartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>

        <dependency>
            <groupId>commons-fileuploadgroupId>
            <artifactId>commons-fileuploadartifactId>
            <version>1.3.3version>
        dependency>

        
        <dependency>
            <groupId>commons-codecgroupId>
            <artifactId>commons-codecartifactId>
        dependency>

        
        <dependency>
            <groupId>org.apache.commonsgroupId>
            <artifactId>commons-lang3artifactId>
        dependency>

        
        <dependency>
            <groupId>org.apache.antgroupId>
            <artifactId>antartifactId>
            <version>1.9.9version>
        dependency>
    dependencies>

项目结构
springboot2.1集成Editor.md_第2张图片
把解压的文件放在static目录下面的editor里面,
创建一个index页面


<html lang="en">
<head>
    <meta charset="UTF-8">
    
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="generator" content="Asciidoctor 1.5.6.1">
    <title>md在线编辑title>
    <link rel="stylesheet" href="/editor/css/editormd.min.css" />
    <script src="/js/jquery.min.js" type="text/javascript" charset="utf-8">script>
    <script src="/editor/src/editormd.js">script>
head>
<body>
<div class="editormd" id="test-editormd">
    <textarea class="editormd-markdown-textarea" name="test-editormd-markdown-doc">textarea>
    
    <textarea class="editormd-html-textarea" name="text">textarea>
div>

<script type="text/javascript">
    $(function() {
        var testEditor;
        testEditor = editormd("test-editormd", {
            placeholder:'本编辑器支持Markdown编辑,左边编写,右边预览',  //默认显示的文字,这里就不解释了
            width: "90%",
            height: 640,
            syncScrolling: "single",
            path: "/editor/lib/",   //就是editor的lib目录
            theme: "dark",//工具栏主题
            previewTheme: "dark",//预览主题
            editorTheme: "pastel-on-dark",//编辑主题
            saveHTMLToTextarea: true,
            emoji: false,
            taskList: true,
            tocm: true,         // Using [TOCM]
            tex: true,                   // 开启科学公式TeX语言支持,默认关闭
            flowChart: true,             // 开启流程图支持,默认关闭
            sequenceDiagram: true,       // 开启时序/序列图支持,默认关闭,
            imageUpload: true,     //开启图片上传
            imageFormats : ["jpg", "jpeg", "gif", "png", "bmp", "webp"],
            imageUploadURL : "/img/imgUpLoad", //上传的路径,就是mvc的controller路径
            toolbarIcons : function() {  //自定义工具栏,后面有详细介绍
                return editormd.toolbarModes['full']; // full, simple, mini
            },
        });
    });
script>
body>
html>

这里需要注意的是jquery的依赖,这里就可以编辑了
但是图片上传还是需要后台配置一下的


@Controller
public class SupplierController {
 	//页面跳转的controller
    @RequestMapping("sys/md/{doc}")
    public String editMdDoc(@PathVariable("doc") String doc){
        return "md/"+doc;
    }
    @RequestMapping("sys/read")
    public String readMd(){
        return "md/show/show";
    }


}
@RestController
@RequestMapping("/img")
public class ImgUpController {
	//上传图片的配置,用的是commons工具,文件存储路径为项目以外
    @PostMapping("/imgUpLoad")
    public MdResult imgUpLoad(@RequestParam(value = "editormd-image-file", required = false) MultipartFile file){
        String rootPath = "F:/download/md/img/";
        String path = rootPath + file.getOriginalFilename();
        try {
            file.transferTo(new File(path));
        } catch (IOException e) {
            e.printStackTrace();
        }

        return new MdResult(1,"上传成功","/image/"+file.getOriginalFilename());
    }
    //MdResult的返回类型,注意返回的格式success,message,url
    public class MdResult {
    public Integer success;

    public String message;

    public String url;

    public MdResult(Integer success, String message, String url) {
        this.success = success;
        this.message = message;
        this.url = url;
    }
}

返回的url就是/image/VCG211164345140.jpg,相当于img标签的链接,因为我这上传的路径不在项目目录下,
配置一下

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
 

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
        registry.addResourceHandler("/image/**").addResourceLocations("file:F:/download/md/img/");
    }
}

目前编辑页面就已经完成了,里面的路径都是写死的,

展示页面


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>md文件展示title>
    <link rel="stylesheet" type="text/css" href="/editor/css/editormd.css" />
    <script src="/js/jquery.min.js" type="text/javascript" charset="utf-8">script>
    <script src="/editor/src/editormd.js" type="text/javascript" charset="utf-8">script>

    <script src="/editor/lib/marked.min.js">script>
    <script src="/editor/lib/prettify.min.js">script>
    <script src="/editor/lib/raphael.min.js">script>
    <script src="/editor/lib/underscore.min.js">script>
    <script src="/editor/lib/sequence-diagram.min.js">script>
    <script src="/editor/lib/flowchart.min.js">script>
    <script src="/editor/lib/jquery.flowchart.min.js">script>
head>
<body>
<div id="wordsView">
            <textarea style="display:none;" name="editormd-markdown-doc" id="mdText">
             textarea>
div>

<script type="text/javascript">
    $(function() {
        $.get('/sys/show/Centos7.md',function(result){
            if(result.errorCode==1){
                return ;
            }else{
                $("#mdText").html(result.data.data);
                wordsView = editormd.markdownToHTML("wordsView", {
                    htmlDecode      : "style,script,iframe",  // you can filter tags decode
                    emoji           : true,
                    taskList        : true,
                    tex             : true,  // 默认不解析
                    flowChart       : true,  // 默认不解析
                    sequenceDiagram : true  // 默认不解析
                });
            }

        });
        //})
    });
script>
body>
html>

里面的js看情况引用,直接全部复制也行
因为这里采用的是读取外部md文件,写一个读取的方法

@RestController
@RequestMapping("/sys")
public class ShowMdController {
	//文件根据需要自己选择
    @GetMapping("/show/{id}")
    public ApiResult showMd(@PathVariable("id")String id){
        String json = "";
        try {
            json = FileUtils.readFileToString(new File("F:/download/md/test.md"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResultUtils.buildSucessObject(json);
    }
}

访问链接就可以了

4. 补充(2019-10-24)

1.返回前端的实例类


public class ResultUtils{
    public static final String SUCESS_MSG = "处理成功";
    public static final String FAILED_MSG = "处理失败";

    public static final Integer SUCESS_CODE = 0;
    public static final Integer FAILED_CODE = 1;
    private ResultUtils(){

    }

    public static ApiResult buildError(Integer errorCode,String msg){
        return new ApiResult(errorCode,msg,null);
    }

    public static ApiResult buildSucessObject(Object data){
        return new ApiResult(SUCESS_CODE,SUCESS_MSG,data);
    }

    public static ApiResult buildSucess(){
        return new ApiResult(SUCESS_CODE,SUCESS_MSG,null);
    }

    public static class ApiResult {
        private ApiResult(Integer errorCode, String msg, Object data) {
            this.errorCode = errorCode;
            this.msg = msg;
            this.data = data;
        }

        /**
         * 错误码
         */
        private Integer errorCode;

        /**
         * 消息提示
         */
        private String msg;

        /**
         * 返回的函数,一般使用Object或者Map
         */
        private Object data;
		
		public Integer getErrorCode() {
            return errorCode;
        }

        public void setErrorCode(Integer errorCode) {
            this.errorCode = errorCode;
        }

        public String getMsg() {
            return msg;
        }

        public void setMsg(String msg) {
            this.msg = msg;
        }

        public Object getData() {
            return data;
        }

        public void setData(Object data) {
            this.data = data;
        }
		
    }

}


2.前面的主题给大家分享一下

{
  "theme": [     //工具栏主题
    "default","dark"
  ],
  "previewTheme": [//预览主题
    "default","dark"
  ],
  "editorTheme": [//编辑主题
    "ambiance",
    "eclipse",
    "mdn-like",
    "mbo",
    "monokai",
    "neat",
    "pastel-on-dark",
    "default",
    "3024-day",
    "3024-night",
    "ambiance",
    "ambiance-mobile",
    "base16-dark",
    "base16-light",
    "blackboard",
    "cobalt",
    "eclipse",
    "elegant",
    "erlang-dark",
    "lesser-dark",
    "mbo",
    "mdn-like",
    "midnight",
    "monokai",
    "neat",
    "neo",
    "night",
    "paraiso-dark",
    "paraiso-light",
    "pastel-on-dark",
    "rubyblue",
    "solarized",
    "the-matrix",
    "tomorrow-night-eighties",
    "twilight",
    "vibrant-ink",
    "xq-dark",
    "xq-light"
  ]
}

5.结束

简单使用就这样子,里面好多可以很灵活的处理,spring的就写的很简单,有兴趣请留言,
转发请注明出处,此文章为原创谢谢!

你可能感兴趣的:(java,markDown)