spring 整合editor.md 实现markdown 编辑

整合一个编辑器,其实很简单。首先找到他的源码,以editor.md 为例:https://github.com/pandao/editor.md
下载后,到examples文件夹看看,看到一个simple.html的例子,这就是可以复制的前端代码:

这里写图片描述

到myeclipse中新建一个应用, 并添加spring支持(公司用jdk1.7,就简单用spring4.2.5, 不用spring boot,理解整合原理就行)

spring 整合editor.md 实现markdown 编辑_第1张图片

着重看下前端的页面:

  • index.jsp,css和js自己拷贝并改下路径
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>


<html lang="zh">
    <head>
        <meta charset="utf-8" />
        <title>Simple example - Editor.md examplestitle>
        <link rel="stylesheet" href="css/style.css" />
        <link rel="stylesheet" href="css/editormd.css" />
        <link rel="shortcut icon" href="https://pandao.github.io/editor.md/favicon.ico" type="image/x-icon" />
        <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">    
    head>
    <body>
        <div id="layout">
            <header>
                <h1>Simple exampleh1>
            header>
            <form action="markdownTest" method="post">
            <div id="test-editormd">
                <textarea style="display:none;" name="markdownContent">textarea>
            div>
            <button type="submit" class="btn btn-info col-md-offset-3 col-md-6">添加button>
                form>
        div>
        <script src="js/jquery.min.js">script>
        <script src="js/editormd.min.js">script>
        <script src="lib/marked.min.js">script>
        <script src="lib/prettify.min.js">script>

        <script src="lib/raphael.min.js">script>
        <script src="lib/underscore.min.js">script>
        <script src="lib/sequence-diagram.min.js">script>
        <script src="lib/flowchart.min.js">script>
        <script src="lib/jquery.flowchart.min.js">script>

        <script src="js/editormd.js">script>
        <script type="text/javascript">
            var testEditor;

            $(function() {
                testEditor = editormd("test-editormd", {
                    width   : "90%",
                    height  : 640,
                    syncScrolling : "single",
                    path    : "lib/",
                    imageUpload : true,
                    imageFormats : ["jpg", "jpeg", "gif", "png", "bmp", "webp"],
                    imageUploadURL : "imageUpload",
                });

                /*
                // or
                testEditor = editormd({
                    id      : "test-editormd",
                    width   : "90%",
                    height  : 640,
                    path    : "../lib/"
                });
                */
            });
        script>
    body>
html>

注意一下,如开启图片上传,要设置:

 imageUpload : true,
 imageFormats : ["jpg", "jpeg", "gif", "png", "bmp", "webp"],
 imageUploadURL : "imageUpload",

其中imageUpload是我的后台处理图片上传的方法,那么我是怎么知道图片上传的请求参数和返回参数的呢?看examples的demo就知道了,首先是返回参数,可以在image-upload.html直接看:

spring 整合editor.md 实现markdown 编辑_第2张图片

至于请求参数,审查一下元素即可,叫editormd-image-file:

这里写图片描述

  • 那么我的后台处理图片上传的方法可以这么写:
package com.wen.controller;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.wen.util.FileUpload;


@Controller
public class MarkDownImageUpload {

    @RequestMapping("imageUpload")
    public void imageUpload(@RequestParam(value = "editormd-image-file", required = true) MultipartFile file,
            HttpServletRequest request, HttpServletResponse response){
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");  
        PrintWriter wirte = null; 
        JSONObject json = new JSONObject();
         try {  
                wirte = response.getWriter();
                //文件存放的路径
                String path = request.getSession().getServletContext().getRealPath("upload");
                String url = "http://localhost:8080" 
                        + request.getContextPath() 
                        + "//upload//"
                        + FileUpload.upload(request, file, path); 
                json.put("success", 1);
                json.put("message", "hello");
                json.put("url", url);
            } catch (Exception e) {  
            }finally{  
                wirte.print(json);  
                wirte.flush();  
                wirte.close();  
            }
    }

}
package com.wen.util;

import java.io.File;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.multipart.MultipartFile;

public class FileUpload {

    /*
     *图片上传工具类 
     */
    public static String upload(HttpServletRequest request, MultipartFile file, String path) {
        String fileName = file.getOriginalFilename();
        fileName=UUID.randomUUID()+fileName.substring(fileName.indexOf("."),fileName.length());
        File targetFile = new File(path, fileName);  
        if(!targetFile.exists()){  
            targetFile.mkdirs();  
        }  
        //保存  
        try {  
            file.transferTo(targetFile);  
        } catch (Exception e) {  
            e.printStackTrace();  
        } 
        return fileName;
    }

}

这样图片上传就没问题了,但是,在正式场合,建议将图片放到第三方的存储平台,不要放在tomcat中,不方便。

  • 显示markdown,还是用example的例子:html-preview-markdown-to-html.html

    WEB-INF/index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>



<html lang="zh">
    <head>
        <meta charset="utf-8" />
        <title>HTML Preview(markdown to html) - Editor.md examplestitle>
        <link rel="stylesheet" href="css/style.css" />
        <link rel="stylesheet" href="css/editormd.css" />
        <link rel="shortcut icon" href="https://pandao.github.io/editor.md/favicon.ico" type="image/x-icon" />
        <style>            
            .editormd-html-preview {
                width: 90%;
                margin: 0 auto;
            }
        style>
    head>
    <body>
        <div id="layout">
            <div id="test-editormd-view">
                <textarea id="append-test" style="display:none;">${markdownContent}textarea>          
            div>
        div>
        
        <script src="js/jquery.min.js">script>
        <script src="js/editormd.min.js">script>
        <script src="lib/marked.min.js">script>
        <script src="lib/prettify.min.js">script>

        <script src="lib/raphael.min.js">script>
        <script src="lib/underscore.min.js">script>
        <script src="lib/sequence-diagram.min.js">script>
        <script src="lib/flowchart.min.js">script>
        <script src="lib/jquery.flowchart.min.js">script>
        <script src="js/editormd.js">script>
        <script type="text/javascript">
            $(function() {
                var testEditormdView

                testEditormdView = 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>
  • 效果:

spring 整合editor.md 实现markdown 编辑_第3张图片

spring 整合editor.md 实现markdown 编辑_第4张图片

源码地址:https://github.com/awhen/MarkDownDemo

你可能感兴趣的:(java)