bzdww

Get answers and suggestions for various questions from here

Use and modify editor.md to implement Markdown editor in JAVA-WEB project

cms

This article was first created in: Using and transforming editor.md to implement the Markdown editor in the JAVA-WEB project - Tintin's blog

Knowing that the image is compressed, the code is not stained. In order to read this article better, please visit the link above to browse.

Introduction to Markdown and Editor.md

Markdwon editor has become more and more popular in the circle of technical workers, simple syntax, unified format, powerful extensions, and most importantly: you can use Markdown to design a wonderful document without any need Your right hand moves from the keyboard to the mouse, which is what I and many programmers love the most. The reason for the long-term use of Leafet is also based on the Markdown editor with a powerful web and client (personal even prefers the client Leafet).

Editor.md is an open source online Markdown editor developed by the Chinese. It is based on front-end JavaScript and does not require background code blessing. It is suitable for any language (only when the image upload function is needed, it needs a little background code to match it, and the rest is given to Editor.md. ), because it was developed by the Chinese, support for Chinese is quite in place. In the process of designing my personal blog, Baidu's ueditor is used as a document editor for a long time. To be honest, configuring the gadget is quite cumbersome, and it is even more annoying to configure ueditor to suit your own mind. bother. After experiencing a bug in the conflict between SpringMVC and ueditor uploading components, there is an impulse to completely abandon ueditor.
I have been using the Markdown editor for Leafet for a long time, and I am looking for a Markdown editor that can replace ueditor. Editor.md is exactly what I want.

Editor.md installation and use

1. Basic use and form submission

Basic use of markdown is quite simple, simpler than ueditor. The Editor.md downloaded from git is version 1.5. There are detailed folders in the archive.

There is a simple example in the examples folder, simple.html, which can be opened in the browser and view the source code. I will make a simple summary here, plus the configuration of the form submission:

  • Load CSS in HTML: editormd.css
  • Load JS in HTML: order is jQuery, editormd.min.js,
  • Write a div node in HTML containing two textareas in the following format: <div class="editormd" id="test-editormd"> <textarea class="editormd-markdown-textarea" name="test-editormd-markdown-doc"></textarea> <!-- 第二个隐藏文本域,用来构造生成的HTML代码,方便表单POST提交,这里的name可以任意取,后台接受时以这个name键为准 --> <textarea class="editormd-html-textarea" name="text"></textarea> </div>
  • Write a javascript in HTML:

<script type="text/javascript">
$(function()
{
editormd("test-editormd",
{
width :
"90%",
height :
640,
syncScrolling :
"single", //你的lib目录的路径,我这边用JSP做测试的
path :
"<%=request.getContextPath()%>/resources/editormd/lib/", //这个配置在simple.html中并没有,但是为了能够提交表单,使用这个配置可以让构造出来的HTML代码直接在第二个隐藏的textarea域中,方便post提交表单。
saveHTMLToTextarea :
true }); }); </script>

The above code knows the typesetting confusion, please visit the original connection to read:

Use and modify editor.md to implement Markdown editor in JAVA-WEB project

OK,这样就完成了一个最简单的editor.md的编辑器了,你可以在这里面书写你熟悉的Markdown文档,里面可以包含代码,右侧有实时的预览。如图所示:


2. Image upload

With the basic Markdown feature, the integrated editor.md is half done, and the next step is to process the image upload.

The syntax for image uploading is ![alt](url) that it is very convenient to embed a ready-made image on the Internet, but if you want to upload a local image, you need to match the background code. I will use JAVA as an example (the official document has a PHP example). SpringMVC and commons-fileupload-1.3.1.jar, simply give a DEMO:

According to the official documentation of Editor.md, the upload image function needs to add a little configuration, as follows:

editormd("test-editormd", {
width :
"90%",
height :
640,
syncScrolling :
"single",
path :
"<%=request.getContextPath()%>/resources/editormd/lib/",
imageUpload :
true,
imageFormats :
["jpg", "jpeg", "gif", "png", "bmp", "webp"],
imageUploadURL :
"/uploadfile",
saveHTMLToTextarea :
true, }); //editor.md期望得到一个json格式的上传后的返回值,格式是这样的: /*
{
success : 0 | 1, // 0 表示上传失败,1 表示上传成功
message : "提示的信息,上传成功或上传失败及错误信息等。",
url : "图片地址" // 上传成功时才返回
}
*/


The above code knows the typesetting confusion, please visit the original connection to read:

Use and modify editor.md to implement Markdown editor in JAVA-WEB project

代码并不难理解,也就加了三行配置,关键的是imageUploadURL : "/uploadfile"这个配置,这里的URL指向了你处理图片上传的action,与之对应的,我的SpringMVC控制器是这样的,这里贴出了整个代码,防止有小伙伴对JAVA以及SpringMVC处理文件上传还不太熟练:

package com.newflypig.jblog.controller; import java.io.File; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.FileUtils; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; @Controller public class UploadController { @RequestMapping (value="/uploadfile",method=RequestMethod.POST) public void hello(HttpServletRequest request,HttpServletResponse response, @RequestParam (value = "editormd-image-file", required = false) MultipartFile attach){ try {
request.setCharacterEncoding(
"utf-8" );
response.setHeader(
"Content-Type" , "text/html" ); String rootPath = request.getSession().getServletContext().getRealPath("/resources/upload/"); /**
* 文件路径不存在则需要创建文件路径
*/
File filePath=new File(rootPath); if(!filePath.exists()){
filePath.mkdirs();
} //最终文件名 File realFile=new File(rootPath+File.separator+attach.getOriginalFilename()); FileUtils.copyInputStreamToFile(attach.getInputStream(), realFile); //下面response返回的json格式是editor.md所限制的,规范输出就OK
response.getWriter().write(
"{\"success\": 1, \"message\":\"上传成功\",\"url\":\"/resources/upload/" + attach.getOriginalFilename() + "\"}" ); } catch (Exception e) { try {
response.getWriter().write(
"{\"success\":0}" ); } catch (IOException e1) {
e1.printStackTrace();
} } } }


The above code knows the typesetting confusion, please visit the original connection to read:

Use and modify editor.md to implement Markdown editor in JAVA-WEB project

这样就完成了图片上传了,上传后,后台action返回了一个url给editor.md,editor.md使用这个url作为你嵌套在文档中的图片url。
这样就大功告成了,是不是很爽,要比ueditor的上传配置简单100倍。

3.Editor.md code black theme

Used to sublime text and other editors, is not a bit of a requirement for the rendering of the code, first screenshots of the two IDEs of the blogger, one is sublime text3, one is myeclipse2015:

I am used to the code style of the black background, I hope that the editor.md can also implement the code black style. Sure enough, the editor.md provides the dark style theme from the 1.5 version, but will make the editing area other than the code black. So, make a small transformation according to your personal needs:

  • First add the style configuration, based on the original editor.md configuration, add configuration items:

$(function() {
editormd("test-editormd",
{
width :
"90%",
height :
640,
syncScrolling :
"single",
path :
"<%=request.getContextPath()%>/resources/editormd/lib/",
imageUpload :
true,
imageFormats :
["jpg", "jpeg", "gif", "png", "bmp", "webp"],
imageUploadURL :
"/uploadfile",
saveHTMLToTextarea :
true, //下面这一行将使用dark主题
previewTheme :
"dark" }); });


The above code knows the typesetting confusion, please visit the original connection to read:

Use and modify editor.md to implement Markdown editor in JAVA-WEB project

配置好dark主题以后,编辑区还是原来的编辑区,预览区已经使用了暗黑模式,但是代码以外的部分也都变成黑色背景了,这不是我想要的,所以我对editormd.css做了一些修正,将dark主题代码以外的部分取消了样式定义,这样预览起来只有代码块是暗黑模式,截图如下:

After modifying editormd.css, don't forget to use CSS compression tool to compress it again and generate editormd.min.css, which can reduce the pressure on the server and improve the loading efficiency. I put the compressed re-generated editormd.min.css out, if necessary, you can download it directly.
Editormd.min.css

4. Display of the document

The code format of the editing area has been adjusted to be our favorite style. When the form POST is submitted, editormd translates our markdown syntax document into HTML language and submits the html string to our background. The HTML should be in the background. Strings are persisted into the database and displayed on the page as they appear.

The specific approach is:

<link rel="stylesheet" href="<%=request.getContextPath()%>/resources/editormd/css/editormd.preview.min.css" />
<link rel="stylesheet" href="<%=request.getContextPath()%>/resources/editormd/css/editormd.css" />
<!-- 因为我们使用了dark主题,所以在容器div上加上dark的主题类,实现我们自定义的代码样式 -->
<div class="content editormd-preview-theme-dark" id="content">${article.text }</div>
<script src="<%=request.getContextPath()%>/resources/js/jquery.min.js"></script>
<script src="<%=request.getContextPath()%>/resources/editormd/lib/marked.min.js"></script>
<script src="<%=request.getContextPath()%>/resources/editormd/lib/prettify.min.js"></script>
<script src="<%=request.getContextPath()%>/resources/editormd/editormd.min.js"></script>
<script type="text/javascript">
editormd.markdownToHTML("content");
</script>


The above code knows the typesetting confusion, please visit the original connection to read:

Use and modify editor.md to implement Markdown editor in JAVA-WEB project

至此,我们所有的工作都完成了。(另外还有些editor.md高级功能,比如[TOC]标签自动生成文档目录结构、流程图语法等,我还没研究,不过现在已经满足我的所有要求了,感兴趣的朋友可以继续阅读examples文件夹中各种示例。)
如果您各项基础知识掌握得都还可以的话,将editor.md这个编辑器引入你的项目是相当轻松加愉快的。写这篇blog也确实因为对这个编辑器的喜爱,加上官方尚未有一个系统的cookbook,都是一个个小demo,希望能帮到想使用editor.md的朋友。