editormd实现Markdown编辑器写文章功能

想在项目里引入Markdown编辑器实现写文章功能,网上找到一款开源的插件editormd.js

介绍网站:https://pandao.github.io/editor.md/examples/index.html

源码:https://github.com/pandao/editor.md,插件代码已经开源到github上了。

可以先git clone下载下来

git clone https://github.com/pandao/editor.md.git

现在介绍一下怎么引入JavaWeb项目里,可以在Webapp(WebContent)文件夹下面,新建一个plugins的文件夹,然后再新建editormd文件夹,文件夹命名的随意。

在官方网站也给出了比较详细的使用说明,因为我需要的个性化功能不多,所以下载下来的examples文件夹下面找到simple.html文件夹

加上样式css文件

<link href="<%=basePath %>plugins/editormd/css/editormd.min.css"
    rel="stylesheet" type="text/css" />

关键的JavaScript脚本

<script type="text/javascript"
    src="<%=basePath %>static/js/jquery-1.8.3.js"></script>
<script type="text/javascript"
    src="<%=basePath %>plugins/editormd/editormd.min.js"></script>
<script type="text/javascript">
    var testEditor;
    
    $(function() {
        testEditor = editormd("test-editormd", {
            width   : "90%",
            height  : 640,
            syncScrolling : "single",
            path    : "<%=basePath %>plugins/editormd/lib/"
        });
    });
</script>

写个jsp页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html>
<html>
<head>
<base href="<%=basePath %>">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Nicky's blog 写文章</title>
<link rel="icon" type="image/png" href="static/images/logo/logo.png">
<link href="<%=basePath %>plugins/editormd/css/editormd.min.css"
    rel="stylesheet" type="text/css" />
<link href="<%=basePath %>static/css/bootstrap.min.css" 
    rel="stylesheet" type="text/css"  />
<style type="text/css">
    #articleTitle{
        width: 68%;
        margin-top:15px;
    }
    #articleCategory{
        margin-top:15px;
        width:10%;
    }
    #btnList {
        position:relative;
        float:right;
        margin-top:15px;
        padding-right:70px;                 
    }
    
</style>
</head>
<body>
    <div id="layout">
        <header>
            文章标题:<input type="text" id="articleTitle" />
            类别:
            <select id="articleCategory"></select>
            <span id="btnList">
                <button type="button" id="publishArticle" onclick="writeArticle.doSubmit();" class="btn btn-info">发布文章</button>
            </span>
        </header>
        <div id="test-editormd">
            <textarea id="articleContent" style="display: none;">
</textarea>
</div>
    </div>
<script type="text/javascript"
    src="<%=basePath %>static/js/jquery-1.8.3.js"></script>
<script type="text/javascript"
    src="<%=basePath %>plugins/editormd/editormd.min.js"></script>
<script type="text/javascript">
    var testEditor;
    
    $(function() {
        testEditor = editormd("test-editormd", {
            width   : "90%",
            height  : 640,
            syncScrolling : "single",
            path    : "<%=basePath %>plugins/editormd/lib/"
        });
        categorySelect.init();
    });

    /* 文章类别下拉框数据绑定 */
    var categorySelect = {
        init: function () {//初始化数据
            $.ajax({
                type: "GET",
                url: 'articleSort/listArticleCategory.do',
                dataType:'json',
                contentType:"application/json",
                cache: false,
                success: function(data){
                    //debugger;
                    data = eval(data) ;
                    categorySelect.buildOption(data);
                }
            });
        },
        buildOption: function (data) {//构建下拉框数据
            //debugger;
            var optionStr ="";
            for(var i=0 ; i < data.length; i ++) {
                optionStr += "<option value="+data[i].typeId+">";
                optionStr += data[i].name;
                optionStr +="</option>";
            }
            $("#articleCategory").append(optionStr);
        }
    }

    /* 发送文章*/
    var writeArticle = {
        doSubmit: function () {//提交
            if (writeArticle.doCheck()) {
                //debugger;
                var title = $("#articleTitle").val();
                var content = $("#articleContent").val();
                var typeId = $("#articleCategory").val();
                $.ajax({
                    type: "POST",
                    url: '<%=basePath %>article/saveOrUpdateArticle.do',
                    data: {'title':title,'content':content,'typeId':typeId},
                    dataType:'json',
                    //contentType:"application/json",
                    cache: false,
                    success: function(data){
                        //debugger;
                        if ("success"== data.result) {
                           alert("保存成功!");
                            setTimeout(function(){
                                window.close();
                            },3000);
                        }
                    }
                });
            }
        },
        doCheck: function() {//校验
            //debugger;
            var title = $("#articleTitle").val();
            var content = $("#articleContent").val();
            if (typeof(title) == undefined || title == null || title == "" ) {
                alert("请填写文章标题!");
                return false;
            }

            if(typeof (content) == undefined || content == null || content == "") {
                alert("请填写文章内容!");
                return false;
            }

            return true;
        }
    }
    
</script>
</body>
</html>

然后后台只要获取一下参数就可以,注意的是path参数要改一下

testEditor = editormd("test-editormd", {
            width   : "90%",
            height  : 640,
            syncScrolling : "single",
            path    : "<%=basePath %>plugins/editormd/lib/"
        });

SpringMVC写个接口获取参数进行保存,项目用了Spring data Jpa来实现

package net.myblog.entity;

import javax.persistence.*;
import java.util.Date;

/**
 * 博客系统文章信息的实体类
 * @author Nicky
 */
@Entity
public class Article {
    
    /** 文章Id,自增**/
    private int articleId;
    
    /** 文章名称**/
    private String articleName;
    
    /** 文章发布时间**/
    private Date articleTime;
    
    /** 图片路径,测试**/
    private String imgPath;
    
    /** 文章内容**/
    private String articleContent;
    
    /** 查看人数**/
    private int articleClick;
    
    /** 是否博主推荐。0为否;1为是**/
    private int articleSupport;
    
    /** 是否置顶。0为;1为是**/
    private int articleUp;
    
    /** 文章类别。0为私有,1为公开,2为仅好友查看**/
    private int articleType;

    private int typeId;


    private ArticleSort articleSort;
    
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Id
    public int getArticleId() {
        return articleId;
    }

    public void setArticleId(int articleId) {
        this.articleId = articleId;
    }

    @Column(length=100, nullable=false)
    public String getArticleName() {
        return articleName;
    }

    public void setArticleName(String articleName) {
        this.articleName = articleName;
    }

    @Temporal(TemporalType.DATE)
    @Column(nullable=false, updatable=false)
    public Date getArticleTime() {
        return articleTime;
    }

    public void setArticleTime(Date articleTime) {
        this.articleTime = articleTime;
    }

    @Column(length=100)
    public String getImgPath() {
        return imgPath;
    }

    public void setImgPath(String imgPath) {
        this.imgPath = imgPath;
    }

    @Column(nullable=false)
    public String getArticleContent() {
        return articleContent;
    }

    public void setArticleContent(String articleContent) {
        this.articleContent = articleContent;
    }

    public int getArticleClick() {
        return articleClick;
    }

    public void setArticleClick(int articleClick) {
        this.articleClick = articleClick;
    }

    public int getArticleSupport() {
        return articleSupport;
    }

    public void setArticleSupport(int articleSupport) {
        this.articleSupport = articleSupport;
    }

    public int getArticleUp() {
        return articleUp;
    }

    public void setArticleUp(int articleUp) {
        this.articleUp = articleUp;
    }

    @Column(nullable=false)
    public int getArticleType() {
        return articleType;
    }

    public void setArticleType(int articleType) {
        this.articleType = articleType;
    }

    public int getTypeId() {
        return typeId;
    }

    public void setTypeId(int typeId) {
        this.typeId = typeId;
    }

    @JoinColumn(name="articleId",insertable = false, updatable = false)
    @ManyToOne(fetch=FetchType.LAZY)
    public ArticleSort getArticleSort() {
        return articleSort;
    }

    public void setArticleSort(ArticleSort articleSort) {
        this.articleSort = articleSort;
    }
    
}

Repository接口:

package net.myblog.repository;

import java.util.Date;
import java.util.List;

import net.myblog.entity.Article;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;

public interface ArticleRepository extends PagingAndSortingRepository<Article,Integer>{
    ...
}

业务Service类:

package net.myblog.service;

import net.myblog.entity.Article;
import net.myblog.repository.ArticleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class ArticleService {
    
    @Autowired ArticleRepository articleRepository;
    /**
     * 保存文章信息
     * @param article
     * @return
     */
    @Transactional
    public Article saveOrUpdateArticle(Article article) {
        return articleRepository.save(article);
    }
}

Controller类:

package net.myblog.web.controller.admin;

import com.alibaba.fastjson.JSONObject;
import net.myblog.core.Constants;
import net.myblog.entity.Article;
import net.myblog.service.ArticleService;
import net.myblog.service.ArticleSortService;
import net.myblog.web.controller.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;


@Controller
@RequestMapping("/article")
public class ArticleAdminController extends BaseController{

    @Autowired
    ArticleService articleService;
    @Autowired
    ArticleSortService articleSortService;
     
    /**
     * 跳转到写文章页面
     * @return
     */
    @RequestMapping(value="/toWriteArticle",method=RequestMethod.GET)
    public ModelAndView toWriteArticle() {
        ModelAndView mv = this.getModelAndView();
        mv.setViewName("admin/article/article_write");
        return mv;
    }

    /**
     * 修改更新文章
     */
    @RequestMapping(value = "/saveOrUpdateArticle", method = RequestMethod.POST)
    @ResponseBody
    public String saveOrUpdateArticle (@RequestParam("title")String title , @RequestParam("content")String content,
        @RequestParam("typeId")String typeIdStr) {
        int typeId = Integer.parseInt(typeIdStr);
        Article article = new Article();
        article.setArticleName(title);
        article.setArticleContent(content);
        article.setArticleTime(new Date());
        article.setTypeId(typeId);
        JSONObject result = new JSONObject();
        try {
            this.articleService.saveOrUpdateArticle(article);
            result.put("result","success");
            return result.toJSONString();
        } catch (Exception e) {
            error("保存文章报错:{}"+e);
            result.put("result","error");
            return result.toJSONString();
        }
    }
    
}

在这里插入图片描述
在这里插入图片描述

然后就在自己的项目里集成成功了,项目链接:https://github.com/u014427391/myblog,自己做的一款开源博客,前端的感谢一个个人网站分享的模板做的,http://www.yangqq.com/download/div/2013-06-15/272.html,感谢作者

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,736评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,167评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,442评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,902评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,302评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,573评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,847评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,562评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,260评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,531评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,021评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,367评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,016评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,068评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,827评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,610评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,514评论 2 269

推荐阅读更多精彩内容