springboot結合開源editor.md集成markdonw編輯器

今天來實現一個簡單的功能,通常blog後臺編輯大多使用的是富文本編輯器,比如百度的Ueditor,比較輕巧的wangEditor,那麼如何使用開源editor.md的markdown呢?

搭建一個springboot+mybatis的項目,然後通過markdown編輯器對錶Content進行插入操作,下面開始

通過IDEA創建一個項目爲markdown的springboot項目,結構如下:


添加依賴pom.xml

 <dependencies>
        <!--thymeleaf-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <!-- web-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- mybatis-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>

        <!--數據庫相關-->
        <!-- mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <!--Druid數據庫連接池-->
         <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.10</version>
        </dependency>

        <!--自動get/set-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <!--測試-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

第一步,整合整合mybatis配置
在application.properties中進行數據源配置以及其他配置項

application.properties

#Tomcat配置
server.port=8081
server.tomcat.uri-encoding=UTF-8

#thymeleaf配置
spring.thymeleaf.prefix=classpath:/templates/
##解決靜態文件訪問不到的情況
spring.mvc.static-path-pattern= /static/**

##mybatis配置
mybatis.type-aliases-package= com.jiangfeixiang.springbootblog.entity
mybatis.mapper-locations= mapper/*.xml

## 數據庫連接配置
## 數據庫連接配置
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/markdown?characterEncoding=utf-8&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=1234

# 連接池補充配置
# 初始化大小,最小,最大
spring.datasource.initialSize: 5
spring.datasource.minIdle: 5
spring.datasource.maxActive: 20
# 配置獲取連接等待超時的時間
spring.datasource.maxWait: 60000
# 配置間隔多久才進行一次檢測,檢測需要關閉的空閒連接,單位是毫秒
spring.datasource.timeBetweenEvictionRunsMillis: 60000
# 配置一個連接在池中最小生存的時間,單位是毫秒
spring.datasource.minEvictableIdleTimeMillis: 300000

spring.datasource.validationQuery: SELECT 1 FROM DUAL
spring.datasource.testWhileIdle: true
spring.datasource.testOnBorrow: false
spring.datasource.testOnReturn: false

# 打開PSCache,並且指定每個連接上PSCache的大小
spring.datasource.poolPreparedStatements: true
spring.datasource.maxPoolPreparedStatementPerConnectionSize: 20
# 配置監控統計攔截的filters,去掉後監控界面sql無法統計,'wall'用於防火牆

spring.datasource.filters: {stat,wall,log4j}
# 通過connectProperties屬性來打開mergeSql功能;慢SQL記錄
spring.datasource.connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000

# 合併多個DruidDataSource的監控數據
spring.datasource.useGlobalDataSourceStat: true

第二步,在dbconfig包下創建DruidConfig類配置druid數據連接池

DruidConfig.class

@Configuration
public class DruidConfig {
    private Logger logger = LoggerFactory.getLogger(DruidConfig.class);

    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DruidDataSource druid(){

        return new DruidDataSource();
    }
    @Bean
    public ServletRegistrationBean druidServlet() {
        logger.info("init Druid Servlet Configuration ");
        ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*");
        Map<String,String> params = new HashMap<>();
        //用戶名
        params.put("loginUsername","姜飛祥");
        //密碼
        params.put("loginPassword","1234");
        //IP白名單 (不填寫代表允許所有IP)
        params.put("allow","");
        //IP黑名單 (存在共同時,deny優先於allow)
        //initParameters.put("deny", "192.168.20.38");
        bean.setInitParameters(params);
        return bean;
    }
    /**
     * druid的過濾器設置
     * @return
     */
    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(new WebStatFilter());
        Map<String,String> initParams = new HashMap<>();
        //排除攔截
        initParams.put("exclusions","*.js,*.css,/druid/*");
        bean.setInitParameters(initParams);
        bean.setUrlPatterns(Arrays.asList("/*"));
        return  bean;
    }
}

以上配置好之後開始完成實體類Content.class,在entity包中創建Content實體類

Content.class

/**
 * @Author: 姜飛祥
 * @Description:
 * @Date: Create in 2019/1/29/0029 13:24
 * 使用lombok註解@Data省略set/get方法
 */

@Data
public class Content {
    private Integer id;
    /**
     * 內容
     */
    private String text;
}

實體類完成之後就是dao與之對應的mapper.xml了,在dao包下創建ContentMapper接口

@Mapper
public interface ContentMapper {

    /**
     * 查詢文本內容
     * @return
     */
   List<Content> getText();

    /**
     * 添加文本內容
     * @param content
     * @return
     */
    int addText(Content content);
}

接口上使用了註解@Mapper,如果不使用此註解的話,可以做哎入口類上添加@MapperScan("com.jiangfeixiang.markdown.dao"),l選擇其一即可如下

@SpringBootApplication
@MapperScan("com.jiangfeixiang.markdown.dao")
public class MarkdownApplication {

    public static void main(String[] args) {
        SpringApplication.run(MarkdownApplication.class, args);
    }

}

下面是對應的ContentMapper.xml,在resources下mapper包中

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.jiangfeixiang.markdown.dao.ContentMapper">

  <!--查詢-->
  <select id="getText" resultType="com.jiangfeixiang.markdown.entity.Content">
    select id,text from content
  </select>

  <!--添加-->
<insert id="addText">
   insert into content(text) values(#{text})
</insert>
</mapper>

到此dao部分已經完成了,下面創建對應的數據庫添加一條數據,進行測試

  • 數據庫名稱請跟進需求在配置文件數據源中進行修改

數據庫sql


SET FOREIGN_KEY_CHECKS=0;

DROP TABLE IF EXISTS `content`;
CREATE TABLE `content` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `text` text,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;


INSERT INTO `content` VALUES ('1', '第一天文本內容');

數據庫創建完成之後,接下來開始進行查詢測試

@RunWith(SpringRunner.class)
@SpringBootTest
public class MarkdownApplicationTests {

    /**
     * 注入ContentMapper接口
     */
    @Autowired
    private ContentMapper contentMapper;

    /**
     * 查詢
     */
    @Test
    public void getText() {
        Content text = contentMapper.getText();
        System.out.println(text);

    }

}

可以在控制檯看到輸出的內容:


下面爲了節約時間,我service接口以及實現類就直接貼代碼參考了,如下

ContentService 接口

public interface ContentService {

    /**
     * 查詢文本內容
     * @return
     */
    List<Content> getText();

    /**
     * 添加文本內容
     * @param content
     * @return
     */
    int addText(Content content);
}

ContentServiceImpl實現類

@Service
public class ContentServiceImpl implements ContentService {

    @Autowired
    private ContentMapper contentMapper;

    /**
     * 查詢
     * @return
     */
    @Override
    public List<Content>getText() {
        return contentMapper.getText();
    }

    /**
     * 添加
     * @param content
     * @return
     */
    @Override
    public int addText(Content content) {
        return contentMapper.addText(content);
    }
}

接下來是ContentController

@Controller
public class ContentController {
    
    @Autowired
    private ContentService contentService;

    /**
     * 編輯頁
     * @return
     */
    @RequestMapping("/edit")
    public String getText(){
        
        return "context";
    }
}

訪問URL路徑進入編輯頁edit.html,在templates/edit.html下,這裏是咱們要實現的開源editor.md markdown編輯器


原材料準備

editor.md

是國人開發的開源在線Markdown編輯器,單純基於前端JavaScript,無需後臺代碼加持,適用於任何語言首頁地址

直接點擊 Github下載 即可
下載好進行解壓之後如下:

  • 接下來直接將examples文件夾中的css、js資源,拷貝到resources下的static中
  • 將examples文件夾中的simple.html示例文件拷貝到工程的templates下面,如下圖


編輯edit.html文件,將資源文件js,css路徑根據你的項目進行調整,由於edit.html中的editormd.css和editormd.min.js沒有,這裏需要進行拷貝進來,拷貝進來後如下圖


拷貝外層的lib目錄並設置edit.html中對應的lib路徑,如圖:


拷貝外層的fonts目錄,並且將外層文件夾images中的loading.gif拷貝到我們項目的images中


最終 調整後的edit.html文件內容爲

最後啓動項目,訪問localhost:8081/edit進入編輯頁面

下面還沒有完,接下來就是開始編寫內容,進行提交到數據庫了

開始提交
在eidt.html頁面中,加入form表單,在text,修改JS,簡單的提交客戶端完成,內容如下:


代碼

<form name="mdEditorForm">
        <div id="test-editormd">
            <textarea name="text" id="text" style="display:none;"> </textarea>
        </div>
    </form>

之後再新增js函數,如圖


代碼

 /**下述爲新增,上面一行記得加逗號結束*/
            /*指定需要顯示的功能按鈕*/
            toolbarIcons : function() {
                return ["undo", "redo", "|","bold", "italic","ucwords","uppercase","lowercase","|","h1","h2","h3","h4","h5","h6","|","list-ul","list-ol","table","datetime","hr",  "||",  "watch", "fullscreen", "preview", "releaseIcon", "index"]
            },

            /*自定義功能按鈕,下面我自定義了2個,一個是發佈,一個是返回首頁*/
            toolbarIconTexts : {
                releaseIcon : "<span bgcolor=\"gray\">發佈</span>",
                index : "<span bgcolor=\"red\">返回首頁</span>",
            },

            /*給自定義按鈕指定回調函數*/
            toolbarHandlers:{
                releaseIcon : function(cm, icon, cursor, selection) {
                        contentCommit();//提交表單代碼在下面
                },
                index : function(){
                    window.location.href = '返回首頁的路徑.html';
                },
            }

另外上面需要提交JS的代碼contentCommit();

/*提交表單的js*/
    function contentCommit(){
        mdEditorForm.method = "post";
        mdEditorForm.action = "addText";//提交至服務器的路徑
        mdEditorForm.submit();
    }

最後在Controller中編寫提交的方法,返回成功頁面

@RequestMapping("/addText")
    public String addText(Content content){
        contentService.addText(content);
        return "success";
    }

因爲查詢沒有顯示數據頁面,爲了節省時間,查詢返回的頁面就不寫了,爲了驗證是否提交成功,咱還在測試裏進行測試



有兩條記錄


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章