个人博客核心功能-富文本编辑器功能的实现

首先看实现结果,需要相互讨论的可以私信我哦!
在这里插入图片描述
在这里插入图片描述
发布成功,样式可以自己改,我只是实现了该功能
在这里插入图片描述
实现过程
1.我这里使用的就是Editor.md,官网下载它:https://pandao.github.io/editor.md/ , 得到它的压缩包!导入到我们idea中
在这里插入图片描述
2.创建实体类

//文章类
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Article implements Serializable {

    private int id; //文章的唯一ID
    private String author; //作者名
    private String title; //标题
    private String content; //文章的内容

}

3.mabitis

@Mapper
@Repository
public interface ArticleMapper {
    //查询所有的文章
    List<Article> queryArticles();

    //新增一个文章
    int addArticle(Article article);

    //根据文章id查询文章
    Article getArticleById(int id);

    //根据文章id删除文章
    int deleteArticleById(int id);

}
<?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.kuang.mapper.ArticleMapper">
    <select id="queryArticles" resultType="Article">
      select * from article
   </select>

    <select id="getArticleById" resultType="Article">
      select * from article where id = #{id}
   </select>

    <insert id="addArticle" parameterType="Article">
      insert into article (author,title,content) values (#{author},#{title},#{content});
   </insert>

    <delete id="deleteArticleById" parameterType="int">
      delete from article where id = #{id}
   </delete>
</mapper>

4.配置springmvc文件映射地址

@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/temp-rainy/**").addResourceLocations("file:D:/temp-rainy/");
    }

}

5.控制类

@Controller
@RequestMapping("/article")
public class ArticleController {

    @Autowired
    private ArticleMapper articleMapper;

    @GetMapping("/toEditor")
    public String toEditor(){
        return "editor";
    }

    @GetMapping("/toEditor1")
    public String toEditor1(){
        return "editor1";
    }

    //保存文章到数据库
    @PostMapping("/addArticle")
    public String addArticle(Article article){
        System.out.println(article);
        articleMapper.addArticle(article);
        return "article";
    }
    //获取文章进行显示
    @GetMapping("/{id}")
    public String show(@PathVariable("id") int id, Model model){
        Article article = articleMapper.getArticleById(id);
        model.addAttribute("article",article);
        return "article";
    }

    // MarkDown博客图片上传问题

    //博客图片上传问题
    @RequestMapping("/file/upload")
    @ResponseBody
    public JSONObject fileUpload(@RequestParam(value = "editormd-image-file", required = true) MultipartFile file, HttpServletRequest request) throws IOException {
        if (file.isEmpty()) {
            System.out.println("文件为空空");
        }
        String fileName = file.getOriginalFilename();  // 文件名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后缀名
        String filePath = "D://temp-rainy//"; // 上传后的路径
        fileName = UUID.randomUUID() + suffixName; // 新文件名
        File dest = new File(filePath + fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //上传路径保存设置

        //获得SpringBoot当前项目的路径:System.getProperty("user.dir")
        //String path = System.getProperty("user.dir")+"/upload/";
        //System.out.println(path);
        //按照月份进行分类:
        //Calendar instance = Calendar.getInstance();
        //String month = (instance.get(Calendar.MONTH) + 1)+"月";
        //path = path+month;

        //File realPath = new File(path);
        /*if (!realPath.exists()){
            realPath.mkdir();
        }*/

        //上传文件地址
        //System.out.println("上传文件保存地址:"+realPath);

        //解决文件名字问题:我们使用uuid;
        //String filename = "ks-"+UUID.randomUUID().toString().replaceAll("-", "");
        //通过CommonsMultipartFile的方法直接写文件(注意这个时候)
        //file.transferTo(new File(realPath +"/"+ filename));

        //给editormd进行回调
        JSONObject res = new JSONObject();
        res.put("url","/temp-rainy/"+"/"+ fileName);
        res.put("success", 1);
        res.put("message", "upload success!");

        return res;
    }


}

6.前端编写文章的html

<!DOCTYPE html>
<html class="x-admin-sm" lang="zh" xmlns:th="http://www.thymeleaf.org">

<head>
    <meta charset="UTF-8">
    <title>Blog</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width,user-scalable=yes, minimum-scale=0.4, initial-scale=0.8,target-densitydpi=low-dpi" />
    <!--Editor.md-->
    <link rel="stylesheet" th: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 class="layui-fluid">
    <div class="layui-row layui-col-space15">
        <div class="layui-col-md12">
            <!--博客表单-->
            <form name="mdEditorForm">

                <div>
                    标题: <input type="text" name="title">
                </div>

                <div>
                    作者: <input type="text" name="author">
                </div>

                <!-- 文章的主体内容 textarea -->
                <div id="article-content">
                    <textarea name="content" id="content" style="display:none;"> </textarea>
                </div>

            </form>

        </div>
    </div>
</div>
</body>

<!--editormd-->
<script th:src="@{/editormd/jquery.min.js}"></script>
<script th:src="@{/editormd/editormd.js}"></script>


<script type="text/javascript">
    var testEditor;

    //window.onload = function(){ }
    $(function() {
        testEditor = editormd("article-content", {
            width:"95%",
            height:500,
            syncScrolling:"single",
            path:"../editormd/lib/",
            // 自定义的增强配置!
            saveHTMLToTextarea:true,    // 保存 HTML 到 Textarea
            emoji:true, // 开启表情的功能! 图片的本地配置!
            // theme: "light",//工具栏主题
            // previewTheme: "dark",//预览主题
            // editorTheme: "pastel-on-dark",//编辑主题
            // markdown的配置!
            tex : true,                   // 开启科学公式TeX语言支持,默认关闭
            flowChart : true,             // 开启流程图支持,默认关闭
            sequenceDiagram : true,       // 开启时序/序列图支持,默认关闭,
            //图片上传
            imageUpload : true,
            imageFormats : ["jpg", "jpeg", "gif", "png", "bmp", "webp"],
            imageUploadURL : "/article/file/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"]
            },
            // 这里的自定义功能就好比,Vue 组件

            /*自定义功能按钮,下面我自定义了2个,一个是发布,一个是返回首页*/
            toolbarIconTexts : {
                releaseIcon : "<span bgcolor=\"gray\">发布</span>",
                index : "<span bgcolor=\"red\">返回首页</span>",
            },

            /*给自定义按钮指定回调函数*/
            toolbarHandlers:{
                releaseIcon : function(cm, icon, cursor, selection) {
                    //表单提交
                    mdEditorForm.method = "post";
                    mdEditorForm.action = "/article/addArticle";//提交至服务器的路径
                    mdEditorForm.submit();
                },
                index : function(){
                    window.location.href = '/';
                },
            }
        });
    });
</script>



</html>

显示的html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title th:text="${article.title}"></title>
</head>
<!--读博客的页面-->

<body>
<div>
    <!--文章头部信息:标题,作者,最后更新日期,导航-->
    <h2 style="margin: auto 0" th:text="${article.title}"></h2>
    作者:<span style="float: left" th:text="${article.author}"></span>
    <!--文章主体内容-->
    <div id="doc-content">
        <textarea style="display:none;" placeholder="markdown" th:text="${article.content}"></textarea>
    </div>

</div>

<!--固定editormd依赖! -->
<link rel="stylesheet" th:href="@{/editormd/css/editormd.preview.css}"/>
<script th:src="@{/editormd/jquery.min.js}"></script>
<script th:src="@{/editormd/lib/marked.min.js}"></script>
<script th:src="@{/editormd/lib/prettify.min.js}"></script>
<script th:src="@{/editormd/lib/raphael.min.js}"></script>
<script th:src="@{/editormd/lib/underscore.min.js}"></script>
<script th:src="@{/editormd/lib/sequence-diagram.min.js}"></script>
<script th:src="@{/editormd/lib/flowchart.min.js}"></script>
<script th:src="@{/editormd/lib/jquery.flowchart.min.js}"></script>
<script th:src="@{/editormd/editormd.js}"></script>

<script type="text/javascript">
    var testEditor;
    $(function () {
        // 绑定我们要渲染页面的 div
        testEditor = editormd.markdownToHTML("doc-content", {//注意:这里是上面DIV的id
            htmlDecode: "style,script,iframe",
            emoji: true,
            taskList: true,
            tocm: true,
            tex: true, // 默认不解析
            flowChart: true, // 默认不解析
            sequenceDiagram: true, // 默认不解析
            codeFold: true
        });
    });
</script>
</body>
</html>

成功结束!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值