editormd實現Markdown編輯器寫文章功能
阿新 • • 發佈:2019-01-13
集成 article 置頂 add 開源 發布 relative ont gets
想在項目裏引入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,感謝作者
editormd實現Markdown編輯器寫文章功能