精华内容
下载资源
问答
  • spring中自定义属性编辑器注入org.springframework.beans.factory.config.CustomEditorConfigurer时报错...
    2019-07-17 13:54:55

    报错信息如下:

    Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'PropertyEditorConfigurer1' defined in class path resource [spring/application-ren.xml]: Initialization of bean failed; nested exception is org.springframework.beans.TypeMismatchException: Failed to convert property value of type 'java.util.LinkedHashMap' to required type 'java.util.Map' for property 'customEditors'; nested exception is java.lang.IllegalArgumentException: Cannot convert value of type 'renchaofeng_propertyEditor.TestPropertyEditor' to required type 'java.lang.Class' for property 'customEditors[renchaofeng_propertyEditor.Education]': PropertyEditor [org.springframework.beans.propertyeditors.ClassEditor] returned inappropriate value of type 'renchaofeng_propertyEditor.TestPropertyEditor'
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:564)
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    	at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:312)
    	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:308)
    	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
    	at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:168)
    	at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:687)
    	at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:525)
    	at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
    	at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
    	at renchaofeng.TestSpring.main(TestSpring.java:11)
    Caused by: org.springframework.beans.TypeMismatchException: Failed to convert property value of type 'java.util.LinkedHashMap' to required type 'java.util.Map' for property 'customEditors'; nested exception is java.lang.IllegalArgumentException: Cannot convert value of type 'renchaofeng_propertyEditor.TestPropertyEditor' to required type 'java.lang.Class' for property 'customEditors[renchaofeng_propertyEditor.Education]': PropertyEditor [org.springframework.beans.propertyeditors.ClassEditor] returned inappropriate value of type 'renchaofeng_propertyEditor.TestPropertyEditor'
    	at org.springframework.beans.AbstractNestablePropertyAccessor.convertIfNecessary(AbstractNestablePropertyAccessor.java:608)
    	at org.springframework.beans.AbstractNestablePropertyAccessor.convertForProperty(AbstractNestablePropertyAccessor.java:615)
    	at org.springframework.beans.BeanWrapperImpl.convertForProperty(BeanWrapperImpl.java:216)
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.convertForProperty(AbstractAutowireCapableBeanFactory.java:1583)
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1542)
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1284)
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
    	... 11 more
    Caused by: java.lang.IllegalArgumentException: Cannot convert value of type 'renchaofeng_propertyEditor.TestPropertyEditor' to required type 'java.lang.Class' for property 'customEditors[renchaofeng_propertyEditor.Education]': PropertyEditor [org.springframework.beans.propertyeditors.ClassEditor] returned inappropriate value of type 'renchaofeng_propertyEditor.TestPropertyEditor'
    	at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:303)
    	at org.springframework.beans.TypeConverterDelegate.convertToTypedMap(TypeConverterDelegate.java:661)
    	at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:227)
    	at org.springframework.beans.AbstractNestablePropertyAccessor.convertIfNecessary(AbstractNestablePropertyAccessor.java:588)
    	... 17 more

    有时我们需要定义属性编辑器,便于将string类型转成我们需要的类型,代码如下:

    package renchaofeng_propertyEditor;
    
    public class Person {
    	private int id;
    	private String name;
    	private Education education;
    	public int getId() {
    		return id;
    	}
    	public void setId(int id) {
    		this.id = id;
    	}
    	public String getName() {
    		return name;
    	}
    	public void setName(String name) {
    		this.name = name;
    	}
    	public Education getEducation() {
    		return education;
    	}
    	public void setEducation(Education education) {
    		this.education = education;
    	}
    	@Override
    	public String toString() {
    		return "Person [id=" + id + ", name=" + name + ", education=" + education + "]";
    	}
    }
    package renchaofeng_propertyEditor;
    
    public class Education {
    	private String country;
    
        private String directory;
    
    	public String getCountry() {
    		return country;
    	}
    
    	public void setCountry(String country) {
    		this.country = country;
    	}
    
    	public String getDirectory() {
    		return directory;
    	}
    
    	public void setDirectory(String directory) {
    		this.directory = directory;
    	}
    }
    package renchaofeng_propertyEditor;
    
    import java.beans.PropertyEditorSupport;
    
    import org.apache.commons.lang3.StringUtils;
    
    public class TestPropertyEditor extends PropertyEditorSupport{
    	 
    	@Override
    	public void setAsText(String text) throws IllegalArgumentException {
    		 if(text == null || StringUtils.isBlank(text)) {
    			 throw new IllegalArgumentException("参数text不能为空");
    		 }else {
    			 String[] StrAddressArr = StringUtils.split(text, ",");
    	            Education add = new Education();
    	            add.setCountry(StrAddressArr[0]);
    	            add.setDirectory(StrAddressArr[1]);
    	            setValue(add);
    		 }
    	}
    }

    然后在spring的配置文件里注入Person类和属性编辑器TestPropertyEditor,如下:

    <bean id="person" class="renchaofeng_propertyEditor.Person">
          <property name="id" value="1003" />
            <property name="name" value="东北大亨" />
            <property name="education" value="中国,北京海淀区清华大学" />
        </bean>
         <!--下面是老版本配置方式,会报上面的错误 -->
          <bean id="PropertyEditorConfigurer1"
            class="org.springframework.beans.factory.config.CustomEditorConfigurer">
            <property name="customEditors">
                <map>
                    <entry key="renchaofeng_propertyEditor.Education">
                        <bean class="renchaofeng_propertyEditor.TestPropertyEditor" />
                    </entry>
                </map>
            </property>
        </bean>
    
    <!--下面是新版本配置方式,改成这种方式就会成功 -->
     <bean id="PropertyEditorConfigurer1"
            class="org.springframework.beans.factory.config.CustomEditorConfigurer">
            <property name="customEditors">
                <map>
                    <entry key="renchaofeng_propertyEditor.Education" 
                           value="renchaofeng_propertyEditor.TestPropertyEditor"/>  
                </map>
            </property>
        </bean>

    原因在于CustomEditorConfigurer类的属性customEditors进行更改,老版本的是定义是private Map customEditors; 而新版本定义如下: private Map<Class<?>, Class<? extends PropertyEditor>> customEditors; 所以要更改一下org.springframework.beans.factory.config.CustomEditorConfigurer的配置方式。

    更多相关内容
  • 富文本编辑器Editor.md入门

    千次阅读 2021-04-13 22:29:18
    Editor.md入门 一、富文本编辑器介绍 什么是富文本编辑器? 我们平时在博客园,或者CSDN等平台进行写作的时候,他们的编辑器就是富文本编辑器。 其实这个就是富文本编辑器,市面上有许多非常成熟的富文本编辑器。这...

    Editor.md入门

    一、富文本编辑器介绍

    什么是富文本编辑器?
    我们平时在博客园,或者CSDN等平台进行写作的时候,他们的编辑器就是富文本编辑器。在这里插入图片描述
    其实这个就是富文本编辑器,市面上有许多非常成熟的富文本编辑器。这个文章有很多介绍https://blog.csdn.net/davidhzq/article/details/100815332想了解的小伙伴可以看一下这里就不一一列举了。
    下面进入我们的主题Editor.md

    二、Editor.md介绍

    Editor.md——功能非常丰富的编辑器,左端编辑,右端预览,非常方便,完全免费

    官网:https://pandao.github.io/editor.md/
    在这里插入图片描述
    我们在官网下载它的压缩包,解压以后,在examples目录下面,可以看到他的很多案例使用。
    然后我们删除多余的文件,把有用的导入项目中。
    在这里插入图片描述
    将多余的文件删除,把文件名改为md(这个随便什么都可以),导入项目中

    三、搭建springboot项目

    1、数据库设计

    article:文章表
    在这里插入图片描述

    CREATE TABLE `article` (
    `id` int(10) NOT NULL AUTO_INCREMENT COMMENT 'int文章的唯一ID',
    `author` varchar(50) NOT NULL COMMENT '作者',
    `title` varchar(100) NOT NULL COMMENT '标题',
    `content` longtext NOT NULL COMMENT '文章的内容',
    PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8
    

    2.创建项目导入web模块

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

    3、导入相关依赖

    <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>fastjson</artifactId>
                <version>1.2.66</version>
            </dependency>
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>1.16.10</version>
            </dependency>
            <!--MySQL驱动-->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.1.49</version>
            </dependency>
            <!--数据源druid-->
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid</artifactId>
                <version>1.1.12</version>
            </dependency>
            <!---->
            <dependency>
                <groupId>log4j</groupId>
                <artifactId>log4j</artifactId>
                <version>1.2.17</version>
            </dependency>
            <!--mybatis-->
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>2.1.4</version>
            </dependency>
            <!--thymeleaf xmlns:th="http://www.thymeleaf.org-->
            <dependency>
                <groupId>org.thymeleaf</groupId>
                <artifactId>thymeleaf-spring5</artifactId>
            </dependency>
            <dependency>
                <groupId>org.thymeleaf.extras</groupId>
                <artifactId>thymeleaf-extras-java8time</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
    
    <resources>
       <resource>
           <directory>src/main/java</directory>
           <includes>
               <include>**/*.xml</include>
           </includes>
           <filtering>true</filtering>
       </resource>
    </resources>
    

    4、编写application.yml配置文件

    这里做了三件事 连接数据库、设置数据源、整合mybatis

    spring:
      datasource:
        username: root
        password: x5
        #?serverTimezone=UTC解决时区的报错
        url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
        driver-class-name: com.mysql.jdbc.Driver
        type: com.alibaba.druid.pool.DruidDataSource
    
        #Spring Boot 默认是不注入这些属性值的,需要自己绑定
        #druid 数据源专有配置
        initialSize: 5
        minIdle: 5
        maxActive: 20
        maxWait: 60000
        timeBetweenEvictionRunsMillis: 60000
        minEvictableIdleTimeMillis: 300000
        validationQuery: SELECT 1 FROM DUAL
        testWhileIdle: true
        testOnBorrow: false
        testOnReturn: false
        poolPreparedStatements: true
    
        #配置监控统计拦截的filters,stat:监控统计、log4j:日志记录、wall:防御sql注入
        #如果允许时报错  java.lang.ClassNotFoundException: org.apache.log4j.Priority
        #则导入 log4j 依赖即可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4j
        filters: stat,wall,log4j
        maxPoolPreparedStatementPerConnectionSize: 20
        useGlobalDataSourceStat: true
        connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
    #整合Mybatis
    mybatis:
      type-aliases-package: com.zhao.pojo
      mapper-locations: classpath:mapper/*.xml
    

    5、实体类

    package com.zhao.pojo;
    
    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    
    import java.io.Serializable;
    
    //文章类
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public class Article implements Serializable {
    
       private int id; //文章的唯一ID
       private String author; //作者名
       private String title; //标题
       private String content; //文章的内容
    
    }
    

    6、mapper接口:

    package com.zhao.mapper;
    
    import com.zhao.pojo.Article;
    import org.apache.ibatis.annotations.Mapper;
    import org.springframework.stereotype.Repository;
    
    import java.util.List;
    
    @Mapper
    @Repository
    public interface ArticleMapper {
       //查询所有的文章
       List<Article> queryArticles();
    
       //新增一个文章
       int addArticle(Article article);
    
       //根据文章id查询文章
       Article getArticleById(int id);
    
       //根据文章id删除文章
       int deleteArticleById(int id);
    
    }
    

    在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.zhao.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>
    

    测试一样搭建的环境是否有问题,没有问题我们就开始学习

    四、文章编辑整合(重点)

    1、导入 editor.md 资源

    主要导入红色框里的
    在这里插入图片描述

    2.editor.html编辑页面

    <!DOCTYPE html>
    <html class="x-admin-sm" lang="zh" xmlns:th="http://www.thymeleaf.org">
    
    <head>
        <meta charset="UTF-8">
        <title>富文本编辑器</title>
        <meta name="renderer" content="webkit">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <!--Editor.md-->
        <link rel="stylesheet" th:href="@{/md/css/editormd.css}"/>
        <link rel="stylesheet" th:href="@{/layui/css/layui.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 class="layui-input" type="text" name="title">
                    </div>
                    <div>
                        作者:<input class="layui-input" type="text" name="author">
                    </div>
                    <div id="article-content">
                        <textarea name="content" id="content" style=""> </textarea>
                    </div>
                </form>
    
            </div>
        </div>
    </div>
    </body>
    
    <!--editormd-->
    <script th:src="@{/js/jquery-2.1.0.js}"></script>
    <script th:src="@{/md/editormd.js}"></script>
    
    <script type="text/javascript">
        var testEditor;
    
        //window.onload = function(){ }
        $(function() {
            testEditor = editormd("article-content", {
                width : "95%",
                height : "1000px",
                syncScrolling : "single",
                path : "../md/lib/", //使用自己的路径
                saveHTMLToTextarea : true,    // 保存 HTML 到 Textarea
                emoji: true,
                theme: "dark",//工具栏主题
                previewTheme: "dark",//预览主题
                editorTheme: "pastel-on-dark",//编辑主题
                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"]
                },
    
                /*自定义功能按钮,下面我自定义了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 = '/article/toEditor';//刷新当前页面
                    },
                }
            });
        });
    </script>
    
    </html>
    

    3、编写Controller,进行跳转,以及保存文章

    package com.zhao.controller;
    
    import com.zhao.mapper.ArticleMapper;
    import com.zhao.pojo.Article;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.*;
    
    @Controller
    @RequestMapping("/article")
    public class ArticleController {
    
        @Autowired
        ArticleMapper articleMapper;
    
    
        @GetMapping("/toEditor")
        public String toEditor() {
            return "editor";
        }
        
        @PostMapping("/addArticle")
        public String addArticle(Article article) {
            articleMapper.addArticle(article);
            return "editor";
        }
    }
    

    到这里我们就可以上传文章了
    在这里插入图片描述
    上传成功,数据库如下
    在这里插入图片描述

    五、图片上传问题

    1、页面代码

    在页面中已经写了图片上传的设置,代码如下

    //图片上传
    imageUpload : true,
    imageFormats : ["jpg", "jpeg", "gif", "png", "bmp", "webp"],
    imageUploadURL : "/article/file/upload", // //这个是上传图片时的访问地址
    

    2、controller层添加图片上传方法

      //博客图片上传问题
        @RequestMapping("/file/upload")
        @ResponseBody
        public JSONObject fileUpload(@RequestParam(value = "editormd-image-file", required = true) MultipartFile file, HttpServletRequest request) throws IOException {
            //上传路径保存设置
    
            //获得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","/upload/"+month+"/"+ filename);
            res.put("success", 1);
            res.put("message", "upload success!");
    
            return res;
        }
    

    3、解决文件回显显示的问题

    设置虚拟目录映射!在我们自己拓展的MvcConfig中进行配置即可!

    package com.zhao.config;
    
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    
    @Configuration
    public class MyMvcConfig implements WebMvcConfigurer {
    
        // 文件保存在真实目录/upload/下,
        // 访问的时候使用虚路径/upload,比如文件名为1.png,就直接/upload/1.png就ok了。
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            registry.addResourceHandler("/upload/**")
                    .addResourceLocations("file:"+System.getProperty("user.dir")+"/upload/");
        }
    
    }
    

    这里运行如果报错可能是没有文件夹,手动创建就行。
    在这里插入图片描述

    六、表情包问题

    自己手动下载,emoji 表情包,放到图片路径下:

    修改editormd.js文件

    // Emoji graphics files url path
    editormd.emoji     = {
       path : "../editormd/plugins/emoji-dialog/emoji/",
       ext   : ".png"
    };
    

    七、文章展示

    1、Controller 中增加方法

    @GetMapping("/{id}")
    public String show(@PathVariable("id") int id,Model model){
       Article article = articleMapper.getArticleById(id);
       model.addAttribute("article",article);
       return "article";
    }
    

    2、编写页面 article.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="" th:text="${article.author}"></span>
        <!--文章主体内容-->
        <div id="doc-content">
            <textarea style="" placeholder="markdown" th:text="${article.content}"></textarea>
        </div>
    
    </div>
    
    <link rel="stylesheet" th:href="@{/md/css/editormd.preview.css}" />
    <script th:src="@{/js/jquery-2.1.0.js}"></script>
    <script th:src="@{/md/lib/marked.min.js}"></script>
    <script th:src="@{/md/lib/prettify.min.js}"></script>
    <script th:src="@{/md/lib/raphael.min.js}"></script>
    <script th:src="@{/md/lib/underscore.min.js}"></script>
    <script th:src="@{/md/lib/sequence-diagram.min.js}"></script>
    <script th:src="@{/md/lib/flowchart.min.js}"></script>
    <script th:src="@{/md/lib/jquery.flowchart.min.js}"></script>
    <script th:src="@{/md/editormd.js}"></script>
    
    
    <script type="text/javascript">
        var testEditor;
        $(function () {
            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>
    

    现在我们就可从新启动项目进行测试了

    八、整体测试

    1、图片上传

    在这里插入图片描述

    2.编辑文章,显示图片

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

    3、文章显示

    在这里插入图片描述

    展开全文
  • 如何在angular项目中使用Editor.md

    千次阅读 2020-07-19 21:42:27
    editor.md是国内开源的一款在线Markdown编辑器,可嵌入的 Markdown 在线编辑器(组件),基于 CodeMirror、jQuery 和 Marked 构建。 GitHub:https://github.com/pandao/editor.md 安装依赖 # npm npm install ...

    editor.md是国内开源的一款在线Markdown编辑器,可嵌入的 Markdown 在线编辑器(组件),基于 CodeMirror、jQuery 和 Marked 构建。

    GitHub:https://github.com/pandao/editor.md

    安装依赖

    # npm
     npm install jquery
     # yarn
     yarn add jquery
    

    资源下载

    下载editor.md的的文件,并放置到assets文件夹中,如src/assets/editor.md/
    也可以通过 NPM 安装:

    npm install editor.md
    

    或者通过 Bower 安装:

    bower install editor.md
    

    本文后面讲的是直接下载文件资源方式。

    配置

    angular.json中的build中配置editor.md的css和js路径

    "styles": [
       "src/assets/md_editor/css/editormd.css",
       "src/assets/md_editor/lib/codemirror/codemirror.min.css",
     ],
    "scripts": [
       "./node_modules/jquery/dist/jquery.js",
       "src/assets/md_editor/lib/flowchart.min.js",
       "src/assets/md_editor/lib/jquery.flowchart.min.js",
       "src/assets/md_editor/js/editormd.min.js",
       "src/assets/md_editor/lib/codemirror/codemirror.min.js",
       "src/assets/md_editor/lib/marked.min.js",
       "src/assets/md_editor/lib/prettify.min.js",
       "src/assets/md_editor/lib/underscore.min.js",
       "src/assets/md_editor/lib/raphael.min.js",
       "src/assets/md_editor/lib/sequence-diagram.min.js"
     ]
    

    在app文件下创建一个editor文件夹,在里面创建一个编辑器配置文件editor-config.ts

    • editor-config.ts
    declare var $: any;
    declare var editormd: any;
    
    export class EditorConfig {
      // public width = '100%';
      public width = '868';
      public height = '558';
      public path = './assets/md_editor/lib/';
      public codeFold: true;
      public placeholder = '请输入正文内容'; // 输入提示
      public searchReplace = true;
      public toolbar = true;
      public emoji = false; // 关闭外部emoji工具
      public taskList = true;
      public tex = true;// 数学公式类默认不解析
      public readOnly = false;
      public tocm = true;
      public watch = false; // 是否右边展示实时预览
      public previewCodeHighlight = true;
      public saveHTMLToTextarea = true; // 保存HTML到Textarea中
      public markdown = '';
      public flowChart = true;//流程图
      public syncScrolling = true;
      public sequenceDiagram = true;//UML时序图
      public imageUpload = true;
      public imageFormats = ['jpg', 'jpeg', 'gif', 'png', 'bmp', 'webp'];
      // public crossDomainUpload = true;
      // public imageUploadURL = ''; // 上传图片的接口
      // public htmlDecode = 'style,script,iframe';    
      // public uploadCallbackURL = ""
      public htmlDecode = "style,script,iframe,sub,sup|on*"; // 开启HTML标签解析,可以过滤html的标签解析,为了安全性,默认不开启
    
      public toolbarIcons = function () {
        // Or return editormd.toolbarModes[name]; // full, simple, mini
        // Using "||" set icons align right.
        return [ "bold","italic","h1","h2","del","|","list-ul","list-ol","hr","quote","code-block","table","link","watch","|","fullscreen","file","imageUpload","|","undo","redo",]
      };
      public toolbarIconsClass = {
        imageUpload: "fa-file-image-o",// 指定一个FontAawsome的图标类
      };
      public toolbarIconTexts = {
        // 如果没有图标,则可以这样直接插入内容,可以是字符串或HTML标签
        // file: `<div><input type="file" name="file" id="uploadImage" class="inputfile" style="position:absolute;opacity:0;" accept="image/png,image/jpeg,image/gif,image/jpg,image/svg" /> 
        // <label for="file" style="cursor:pointer;">上传文件</label></div>`
      };
    
      // 自定义工具栏按钮的事件处理
      public toolbarHandlers = {
        /**
         * @param {Object}      cm         CodeMirror对象
         * @param {Object}      icon       图标按钮jQuery元素对象
         * @param {Object}      cursor     CodeMirror的光标对象,可获取光标所在行和位置
         * @param {String}      selection  编辑器选中的文本
         */
        imageUpload: function (cm, icon, cursor, selection) {
          // deal upload event
          $('#uploadImage').click();
          $('#uploadImage').unbind().bind("change", e => {
            let fd = new FormData();
            // 添加到fd对象中等待提交
            fd.append("files", e.target['files'][0]);
            if(!fd) return;
            $.ajax({
              type: 'post',
              url: '/api/v1/upload',
              data: fd,
              cache: false,
              contentType: false,
              processData: false,
              success: data => {
                if (data && data.length > 0) {
                  // cm.replaceSelection("![](http://10.0.10.7:10020" + data[0] + ")" + selection);
                  // 生产环境使用相对路径
                  cm.replaceSelection("![](" +  data[0] + ")" + selection);
                }
              }
            })
          })
          console.log("imageUpload =>", icon.html());
        },
      };
    
      // 用于增加自定义工具栏的功能,可以直接插入HTML标签,不使用默认的元素创建图标
        public toolbarCustomIcons =  {
          file: `<input type="file" name="file" id="uploadImage" class="inputfile" style="position:absolute;opacity:0;" accept="image/png,image/jpeg, image/gif,image/jpg,image/svg,image/xbm,image/pgm,image/xpm" /> `
      };
      public lang = {
        toolbar: {
          imageUpload: "图片上传",  // 自定义按钮的提示文本,即title属性
        }
      };
    
      public editorFunction = '';//定义调用的方法
      constructor() { }
    }
    

    在具体组件中使用

    • html
    <div id="markdown" >
       <textarea id="editText" style="display: block;"></textarea>
    </div>
    
    • ts
    import { EditorConfig } from 'xxx/editor-config';//config文件所在路径
    
    editor:any;
    conf = new EditorConfig();
    showInfo:string;//编辑器内容
    
    constructor(){}
    
    ngAfterViewInit(): void {
        this.createEditor();
    }
    
    createEditor(){
        this.editor = editormd("markdown", this.conf); // 创建编辑器
        // //解决右侧预览偶尔显示不出来的问题(编辑功能下的md)
        $("#markdown.editormd-preview-container")[0].innerHTML = this.showInfo;
        // 在没有开预览模式下获取编辑状态下的值
       // let iputData = $('#markdown .editormd-markdown-textarea').val();
       // 编辑器事件监听
        this.editor.on('change', ()=> {
          const textarea = $("#editText");
          const value= {
            textarea:textarea.val()
          }
          this.showInfo= value.textarea
        });
      }
    

    注意: 由于editor.md编辑器中自带一些图片和emoji资源,需要从github或者外网加载过来,这样就会对网页性能有一些影响,有需要可以考虑在样式文件中替换掉。还有一些加载空表格和图片上传组件的问题,这里就不赘述了。

    展开全文
  • 1、代码 <!... <html lang="zh"> <head>...meta charset="utf-8" />...Simple example - Editor.md examples</title> <link rel="stylesheet" href="css/style.css" /> <link r

    1、代码

    <!DOCTYPE html>
    <html lang="zh">
        <head>
            <meta charset="utf-8" />
            <title>Simple example - Editor.md examples</title>
            <link rel="stylesheet" href="css/style.css" />
            <link rel="stylesheet" href="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>Simple example</h1>
                </header>
                <div id="test-editormd">
                    <textarea style="display:none;">[TOC]#Disabled options</textarea>
                </div>
            </div>
            <script src="js/jquery.min.js"></script>
            <script src="js/editormd.min.js"></script>
            <script type="text/javascript">
    			var testEditor;
    
                $(function() {
                    testEditor = editormd("test-editormd", {
                        width   : "90%",
                        height  : 640,
                        syncScrolling : "single",
                        path    : "lib/",
    					imageUpload : true,
                        imageFormats : ["jpg", "jpeg", "gif", "png", "bmp", "webp"], 
                        imageUploadURL : "/AEBrvTkjOg.php/ajax/uploadByEditormd", // 文件上传的处理请求!
    
                    });
                    
                    /*
                    // or
                    testEditor = editormd({
                        id      : "test-editormd",
                        width   : "90%",
                        height  : 640,
                        path    : "../lib/"
                    });
                    */
                });
            </script>
        </body>
    </html>
    

    2、上传图片

            $savePath = ROOT_PATH  . '\public\uploads\md\\'; //实际保存路径
            $saveURL = config('upload.cdnurl')  . '/uploads/md/'; //返回路径(带域名)
            $formats  = array(
                'image' => array('gif', 'jpg', 'jpeg', 'png', 'bmp')
            );
    
            $name = 'editormd-image-file';
    
            if (isset($_FILES[$name]))
            {
    
                $imageUploader = new \app\admin\controller\EditormdUploaderReal($savePath, $saveURL, $formats['image']);  // Ymdhis表示按日期生成文件名,利用date()函数
    
                $imageUploader->config(array(
                    //'maxSize' => 1024,        // 允许上传的最大文件大小,以KB为单位,默认值为1024
                    //'cover'   => true,         // 是否覆盖同名文件,默认为true
                ));
    
                if ($imageUploader->upload($name))
                {
                    $imageUploader->message('上传成功!', 1);
                }
                else
                {
                    $imageUploader->message('上传失败!', 0);
                }
            }
    

    3、示例
    点击查看示例

    展开全文
  • 百度UEditor编辑器之配置文件:ueditor.config.js,可以在这里配置整个编辑器的特性。
  • WangEditor富文本编辑器图片上传踩坑之路

    万次阅读 热门讨论 2019-04-03 17:42:54
    editor.customConfig.uploadImgServer = '/fileUpload'; editor.customConfig.debug = true; //自定义上传图片事件 editor.customConfig.uploadImgHooks = { before: function (xhr, editor, files) { }, ...
  • java.lang.NoSuchMethodException:xxxx.()

    千次阅读 2018-07-01 15:27:22
    今天想实现一个继承了接口即可在项目启动时初始化接口的实现方法的功能,但是项目启动时出现了这个异常:最后发现原因是:由于我是先通过包扫描获取所有的Class再获取该接口的实现类,获取该接口的实现类使用的方法...
  • 解决:java.lang....java.lang.IllegalStateException: Failed to load property source from location 'classpath:/config/application.yml' at org.springframework.boot.context.config.ConfigFileA
  • // 下面是最重要的的方法 this.editor.config.uploadImgHooks = { before: function (xhr, editor, files) { // 图片上传之前触发 // xhr 是 XMLHttpRequst 对象,editor 是编辑器对象,files 是选择的图片文件 // ...
  • java.lang.IllegalStateException: failed to create a child event loop at io.netty.util.concurrent.MultithreadEventExecutorGroup.(MultithreadEventExecutorGroup.java:88) at io.netty.util.concurrent....
  • 错误原因: 前端对GET请求的参数进行拼接发送至后台时,拼接的参数有异常,导致后台无法正常解析,这是前端的锅。 这里是把有一个用map存放的查询参数为空时,生成了一个无意义的拼接后缀,导致了出错... config.par
  • Markdown编辑器Editor.md集成使用

    千次阅读 2019-05-19 22:01:27
    一、下载插件 项目地址:http://pandao.github.io/editor.md/ ...link rel="stylesheet" href="lib/js/editor.md-master/css/editormd.css" /> //依赖jquery <script type="text/javascript" src="lib/j...
  • but when I run app in some device(Samsung Galaxy S5) I get this error: java.lang.IllegalStateException: Unable to create directory: /storage/emulated/0/my file name and this is caused in ...
  • wangEditor编辑器使用

    千次阅读 2019-04-25 12:40:03
    editor.customConfig.uploadImgServer=’/wangeditorTest/editor/upload’; // 设置图片大小限制为 3M editor.customConfig.uploadImgMaxSize = 3 * 1024 * 1024; // 限制一次最多上传 5 张图片,默认是10000张...
  • No converter found capable of converting from type [java.lang.String] to type [java.util.Map<java.lang.String, java.lang.String>]错误的一个可能原因 在启动springboot项目时报错,具体如下: s....
  • 因为上传图片的问题使用过了各种富文本,最后发现还是这个比较好用。分享记录一下。 安装 npm install wangeditor --save 新建一个wangeditor.vue...div class="editor"> <div ref="toolbar" class="toolb...
  • 一直在使用 Editor.md 插件作为博客的编辑器,用着挺好,但是在全屏下编辑时,每次想预览或者保存又必须切换到非全屏状态下才可以点击按钮,用着不舒服,所以花了一点时间在工具栏上增加了预览、保存、发布三个按钮...
  • 编辑器一般多使用在一些论坛网或博客网站中,现在就讲解一下编辑器在页面中用Jquery怎么生成 ...script type="text/javascript" charset="utf-8" src="~/Content/ueditor/ueditor.config.js"></script> <...
  • 下载安装 npm i wangeditor --save ...template lang="html"> <div id="editor"> </div> </template> <script> import E from 'wangeditor' export default { name: 'Editor',
  • lang: function (newLang) { this.editor.getSession().setMode('ace/mode/' + newLang) } }, mounted () { let vm = this require('brace/ext/emmet') require('brace/ext/language_tools') let editor = ...
  • 场景:nacos_order01服务调用nacos_login01服务【springcloud】 原因:你的服务名字不能有下划线,换成横杠: 改为横杠即可
  • Editor API 文档

    千次阅读 2015-09-08 16:23:39
    UEditor API 文档 ...editor.js, UE.Utils, UE.EventBase, UE.browser, core/dom/dtd.js, UE.dom.domUtils, UE.dom.Range, core/dom/Selection.js, plugins/serialize.js 编辑器主类,包含
  • editor.customConfig.uploadImgServer = '/upload/image.do' // 上传图片到服务器 editor.customConfig.uploadImgMaxSize = 2 * 1024 * 1024; // 将图片大小限制为 2M editor.customConfig.uploadImgMaxLength = ...
  • vue使用富文本编辑器上传图片: 我是用的是wangEditor 富文本编辑器 demo:http://www.wangeditor.com/ 1).安装依赖:npm install wangeditor 2).... ...template lang="html"> <div cl...
  • 下面是我开发项目中遇到的问题,Caused by: java.lang.IllegalArgumentException: Original must not be null,提示这个错误,百思不得其解。最后面不断的google,spring配置Aop配置相关的文章,最后硬着头皮去看看...
  • 格式:app.config['SECRET_KEY'] = 'passwd you want' 解释:为了防止表单中出现CSRF跨站脚本攻击,故加密一个参数,来验证是否真是用户所提交的表单 1.3 开始 导入 from flask_wtf import FlaskForm from ...
  • 1、下载插件 ...template lang="html"> <div class="editor"> <!-- <div ref="toolbar" class="toolbar"></div> --> <div ref="editor" class="text"></div
  • vue 安装npm i wangeditor --save 创建一个editoritem组件 components/editoritem.vue ...divclass="editor"> <div ref="toolbarContainer"class="toolbar"id="toolbar-container"> </div> <...
  • wangeditor上传单张图片

    千次阅读 2018-10-25 20:44:10
     第一次使用wangeditor算是遇到了很多坑,因为网上很多的都是用到java框架的,而框架我又没有学,经过两天的奋斗,算是初步解决上传一张图片的问题以及Tomcat重启后图片被删除的问题。...%@ page lang...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 8,406
精华内容 3,362
关键字:

editor.config.lang

友情链接: fft.zip