SpringBoot 整合 Editormd
Editormd 下载
这边我已经把需要踩得坑都整理好了,直接下载
链接:/s/1FcPX44eZTGhbFl9WLzjfKw
提取码:sdkz
1.依赖注入
<description>Demo project for Spring Boot</description><properties><java.version>1.8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.1.4</version></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope></dependency><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.62</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-test</artifactId><version>2.5.7</version><scope>test</scope></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>3.8.1</version><scope>test</scope></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><scope>test</scope></dependency><dependency><groupId>org.junit.jupiter</groupId><artifactId>junit-jupiter-api</artifactId><version>5.7.2</version><scope>test</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><scope>test</scope></dependency></dependencies>
2.数据库表的创建
3.application.yml
server:port:8081spring:datasource:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://localhost:3306/testa?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=trueusername: rootpassword: 123456thymeleaf:mode: HTMLencoding: utf-8cache: falseprefix: classpath:static/html/web:resources:static-locations: classpath:static/mybatis:mapper-locations: classpath:/mapper/*.xmlresources:static-locations: classpath:/META-INF/resources/,classpath:/resources/, classpath:/static/, classpath:/public/, classpath:/editormd/mvc:view:prefix: html/suffix: .htmlstatic-path-pattern: /**
4.整个项目目录
5.静态资源过滤
@Configurationpublic class MyMvcConfig implements WebMvcConfigurer {@Overridepublic void addResourceHandlers(ResourceHandlerRegistry registry) {//过滤静态资源 会到这个目录里 为markdown图片上传做准备registry.addResourceHandler("/upload/**").addResourceLocations("file:" + FileUtil.PATH);}}
也可以这样直接写
6.工具类
public class FileUtil {//文件存放的路径 若没有 会自动创建public static final String PATH=System.getProperty("user.dir")+"/src/main/resources/static/upload/";/*** 上传文件 如果上传错误 会返回空的地址 注意 返回的地址是用来回显的 所以不要返回布尔类型*/public static String upload(MultipartFile multipartFile) {if(multipartFile.isEmpty()) {return "";}String filename = multipartFile.getOriginalFilename();File file = new File(PATH);if (!file.exists()) {//使用mkdirs 若某个目录不存在 也会一起创建file.mkdirs();}//为了不使得图片名字重复 使用uuid拼接int i = filename.lastIndexOf(".");String suffix = filename.substring(i-1);String newFileName = UUID.randomUUID().toString() + suffix;try {multipartFile.transferTo(new File(PATH+newFileName));} catch (IOException e) {e.printStackTrace();return "";}return newFileName;}}
7.controller类
@Controllerpublic class ArticleController {@ResourceArticleService articleService;@GetMapping("edit")public String edit() {return "edit";}@PostMapping("edit/upload")@ResponseBodypublic JSONObject fileUpload(@RequestParam(value = "editormd-image-file", required = true) MultipartFile file, HttpServletRequest request) throws IOException {String uploadname = FileUtil.upload(file);//给editormd进行回调JSONObject res = new JSONObject();res.put("url", "/upload/" + uploadname);res.put("success", 1);res.put("message", "upload success!");return res;}@PostMapping("save")@ResponseBodypublic String save(Article article) {System.out.println(article);int i = articleService.insertArticle(article);if (i == 1) {System.out.println(1111);return "发布成功";} else {System.out.println(2222);return "失败了....";}}@RequestMapping("/get/{id}")public ModelAndView getArticleById(@PathVariable(name = "id")int id) {System.out.println(id);ModelAndView modelAndView = new ModelAndView();Article article = articleService.getArticleById(id);System.out.println("11111111111111111");modelAndView.setViewName("article");if(article == null) {modelAndView.addObject("article", new Article());}modelAndView.addObject("article", article);return modelAndView;}}
8.service 层
@Servicepublic class ArticleService {@ResourceArticleMapper articleMapper;public int insertArticle(Article article){return articleMapper.insertArticle(article);}public Article getArticleById(int id) {return articleMapper.getArticleById(id);}}
9.dao层
public interface ArticleMapper {public int insertArticle(Article article);public Article getArticleById(int id);}
10.ArticleMapper.xml
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapperPUBLIC "-////DTD Mapper 3.0//EN""/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.peng.editormd.dao.ArticleMapper"><insert id="insertArticle" parameterType="com.peng.editormd.entity.Article" >insert into article(title,author,content) values (#{title},#{author},#{content})</insert><select id="getArticleById" resultType="com.peng.editormd.entity.Article" parameterType="int">select * from article where id = #{id};</select></mapper>
11.前端页面 edit.html
需要引入editormd.css jq和editormd.js,注意路径!!!!!!!!!!!!!!!!!
<!doctype html><html lang="en" xmlns:th=""><head><meta charset="UTF-8"><title>问答</title><link rel="stylesheet" href="../editormd/css/editormd.css"/></head><body><div><form action="/save" method="post">作者 <input type="text" name="author"><br>标题<input type="text" name="title"><div id="blog-content"><textarea required name="content" id="content" style="display:none;" rows="3"class="form-control"> </textarea></div><br><input type="submit" value="发布文章"></form></div><!--/editormd/js/jquery-3.5.1.min.js--><script src="../editormd/js/jquery-3.5.1.min.js"></script><script src="../editormd/editormd.js"></script><script type="text/javascript">var testEditor;$(function () {//根据id来选择对应的textareatestEditor = editormd("blog-content", {width: "100%",height: 500,syncScrolling: "single",path: "../editormd/lib/", //对应的lib目录不要弄错saveHTMLToTextarea: true, // 保存 HTML 到 Textarea// [TOCM] [TOC] 自动生成目录tocm: true,tocContainer: "",tocDropdown: false,tocStartLevel: 1,// Parse beginning of H2, Default value 1emoji: true,tex: true, // 开启科学公式TeX语言支持,默认关闭flowChart: true, // 开启流程图支持,默认关闭sequenceDiagram: true, // 开启时序/序列图支持,默认关闭,//图片上传imageUpload: true,imageFormats: ["jpg", "jpeg", "gif", "png", "bmp", "webp"],imageUploadURL: "../edit/upload",onload: function () {console.log('onload', this);},/*指定需要显示的功能按钮*/toolbarIcons : function() {return ["undo","redo","|","bold","del","italic","quote","ucwords","uppercase","lowercase","|","h1","h2","h3","h4","h5","h6","|","list-ul","list-ol","hr","|","link","reference-link","image","code","preformatted-text","code-block","table","datetime","emoji","html-entities","pagebreak","|","goto-line","watch","preview","fullscreen","clear","search","|","help","info","releaseIcon", "index"]},onfullscreen: function () {console.log("onfullscreen");document.getElementsByClassName("navbar")[0].style.display = "none";},onfullscreenExit: function () {console.log("onfullscreenExit");document.getElementsByClassName("navbar")[0].style.display = "";}});});</script></body></html>
12.前端页面 article.html
<!DOCTYPE html><html lang="en" xmlns:th=""><head><meta charset="UTF-8"><title>文章</title><link rel="stylesheet" href="../editormd/examples/css/style.css" /><link rel="stylesheet" href="../editormd/css/editormd.css" /><link rel="shortcut icon" href="https://pandao.github.io/editor.md/favicon.ico" type="image/x-icon" /></head><body><div id="layout"><header><h1 th:text="${article.title}"></h1><h2 th:text="${article.author}"></h2></header><div id="test-editormd"><textarea style="display:none;" th:text="${article.content}"></textarea></div></div><!--// 一个JS文件都不能少,少一个便无法渲染。注意静态资源路径问题--><script src="../editormd/js/jquery-3.5.1.min.js"></script><script src="../editormd/lib/marked.min.js"></script><script src="../editormd/lib/prettify.min.js"></script><script src="../editormd/lib/raphael.min.js"></script><script src="../editormd/lib/underscore.min.js"></script><script src="../editormd/lib/sequence-diagram.min.js"></script><script src="../editormd/lib/flowchart.min.js"></script><script src="../editormd/lib/jquery.flowchart.min.js"></script><script src="../editormd/editormd.min.js"></script><script type="text/javascript">var testEditor;$(function () {testEditor = editormd.markdownToHTML("test-editormd", {width: "90%",height: 700,path: "../editormd/lib/",preview: true,watch: true,editor: false,})})</script></body></html>