010.UEditor文档

作者: 胖先森 | 来源:发表于2017-11-27 22:15 被阅读0次

UEditor的简单使用

在Java Web阶段和SSM框架阶段,我们的课程设计中都会使用到富文本编辑器,目前流行的编辑器很多

KindEditor/CKEditor/UEditor/WangEditor等,这里我们使用的是百度开源的,这里我们使用JSP的版本

这部分属于自学内容,请各位同学根据文档完成下面配置过程

1.下载UEditor

网址: http://ueditor.baidu.com/website/download.html

image

2.新建动态的Web项目

因为我使用的是SpringMVC框架,如果使用Java Web阶段是比较简单的.

请注意要排除静态资源

<!-- 4.1 静态资源排除方案1 -->
<mvc:default-servlet-handler default-servlet-name="default"/>

将下载的文档解压后,复制到WebContent的resource文件夹下,如图所示:

image

3.显示富文本编辑器

  • 添加UEditor需要的Jar包

    image

    将红色部分的jar包复制添加到WEB-INF/lib下

  • 显示富文本编辑器

    根据示例中的index.html或者官方文档给的示例,将富文本编辑器进行显示,因为我们将所有的JSP都放置到WEB-INF文件夹

    • 新建Controller完成跳转

      @Controller
      public class TestController {
          @GetMapping("/show")
          public String showUE(){
              return "jsp/ueditor";
          }
      }
      
    • 显示富文本编辑器ueditor.jsp

      <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
      <%
          String path = request.getContextPath();
          String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
      %>
      <!DOCTYPE HTML>
      <html>
          <head>
              <base href="<%=basePath%>">
              <meta charset="UTF-8">
              <title>富文本编辑器</title>
              <script type="text/javascript" charset="utf-8" src="resource/ueditor/ueditor.config.js"></script>
              <script type="text/javascript" charset="utf-8" src="resource/ueditor/ueditor.all.min.js"> </script>
              <!--建议手动加在语言,避免在ie下有时因为加载语言失败导致编辑器加载失败-->
              <!--这里加载的语言文件会覆盖你在配置项目里添加的语言类型,比如你在配置项目里配置的是英文,这里加载的中文,那最后就是中文-->
              <script type="text/javascript" charset="utf-8" src="resource/ueditor/lang/zh-cn/zh-cn.js"></script>
              <style type="text/css">
                  div{
                      width:100%;
                  }
              </style>
      </head>
      <body>
          <div>
              <h1>完整demo</h1>
              <script id="editor" type="text/plain" style="width:1024px;height:500px;"></script>
          </div>
          <div id="btns">
              <div>
                  <button onclick="getAllHtml()">获得整个html的内容</button>
                  <button onclick="getContent()">获得内容</button>
                  <button onclick="setContent()">写入内容</button>
                  <button onclick="setContent(true)">追加内容</button>
                  <button onclick="getContentTxt()">获得纯文本</button>
                  <button onclick="getPlainTxt()">获得带格式的纯文本</button>
                  <button onclick="hasContent()">判断是否有内容</button>
                  <button onclick="setFocus()">使编辑器获得焦点</button>
                  <button onmousedown="isFocus(event)">编辑器是否获得焦点</button>
                  <button onmousedown="setblur(event)" >编辑器失去焦点</button>
          
              </div>
              <div>
                  <button onclick="getText()">获得当前选中的文本</button>
                  <button onclick="insertHtml()">插入给定的内容</button>
                  <button id="enable" onclick="setEnabled()">可以编辑</button>
                  <button onclick="setDisabled()">不可编辑</button>
                  <button onclick=" UE.getEditor('editor').setHide()">隐藏编辑器</button>
                  <button onclick=" UE.getEditor('editor').setShow()">显示编辑器</button>
                  <button onclick=" UE.getEditor('editor').setHeight(300)">设置高度为300默认关闭了自动长高</button>
              </div>
          
              <div>
                  <button onclick="getLocalData()" >获取草稿箱内容</button>
                  <button onclick="clearLocalData()" >清空草稿箱</button>
              </div>
          
          </div>
          <div>
              <button onclick="createEditor()">
              创建编辑器</button>
              <button onclick="deleteEditor()">
              删除编辑器</button>
          </div>
          
          <script type="text/javascript">
          
              //实例化编辑器
              //建议使用工厂方法getEditor创建和引用编辑器实例,如果在某个闭包下引用该编辑器,直接调用UE.getEditor('editor')就能拿到相关的实例
              var ue = UE.getEditor('editor');
          
          
              function isFocus(e){
                  alert(UE.getEditor('editor').isFocus());
                  UE.dom.domUtils.preventDefault(e)
              }
              function setblur(e){
                  UE.getEditor('editor').blur();
                  UE.dom.domUtils.preventDefault(e)
              }
              function insertHtml() {
                  var value = prompt('插入html代码', '');
                  UE.getEditor('editor').execCommand('insertHtml', value)
              }
              function createEditor() {
                  enableBtn();
                  UE.getEditor('editor');
              }
              function getAllHtml() {
                  alert(UE.getEditor('editor').getAllHtml())
              }
              function getContent() {
                  var arr = [];
                  arr.push("使用editor.getContent()方法可以获得编辑器的内容");
                  arr.push("内容为:");
                  arr.push(UE.getEditor('editor').getContent());
                  alert(arr.join("\n"));
              }
              function getPlainTxt() {
                  var arr = [];
                  arr.push("使用editor.getPlainTxt()方法可以获得编辑器的带格式的纯文本内容");
                  arr.push("内容为:");
                  arr.push(UE.getEditor('editor').getPlainTxt());
                  alert(arr.join('\n'))
              }
              function setContent(isAppendTo) {
                  var arr = [];
                  arr.push("使用editor.setContent('欢迎使用ueditor')方法可以设置编辑器的内容");
                  UE.getEditor('editor').setContent('欢迎使用ueditor', isAppendTo);
                  alert(arr.join("\n"));
              }
              function setDisabled() {
                  UE.getEditor('editor').setDisabled('fullscreen');
                  disableBtn("enable");
              }
          
              function setEnabled() {
                  UE.getEditor('editor').setEnabled();
                  enableBtn();
              }
          
              function getText() {
                  //当你点击按钮时编辑区域已经失去了焦点,如果直接用getText将不会得到内容,所以要在选回来,然后取得内容
                  var range = UE.getEditor('editor').selection.getRange();
                  range.select();
                  var txt = UE.getEditor('editor').selection.getText();
                  alert(txt)
              }
          
              function getContentTxt() {
                  var arr = [];
                  arr.push("使用editor.getContentTxt()方法可以获得编辑器的纯文本内容");
                  arr.push("编辑器的纯文本内容为:");
                  arr.push(UE.getEditor('editor').getContentTxt());
                  alert(arr.join("\n"));
              }
              function hasContent() {
                  var arr = [];
                  arr.push("使用editor.hasContents()方法判断编辑器里是否有内容");
                  arr.push("判断结果为:");
                  arr.push(UE.getEditor('editor').hasContents());
                  alert(arr.join("\n"));
              }
              function setFocus() {
                  UE.getEditor('editor').focus();
              }
              function deleteEditor() {
                  disableBtn();
                  UE.getEditor('editor').destroy();
              }
              function disableBtn(str) {
                  var div = document.getElementById('btns');
                  var btns = UE.dom.domUtils.getElementsByTagName(div, "button");
                  for (var i = 0, btn; btn = btns[i++];) {
                      if (btn.id == str) {
                          UE.dom.domUtils.removeAttributes(btn, ["disabled"]);
                      } else {
                          btn.setAttribute("disabled", "true");
                      }
                  }
              }
              function enableBtn() {
                  var div = document.getElementById('btns');
                  var btns = UE.dom.domUtils.getElementsByTagName(div, "button");
                  for (var i = 0, btn; btn = btns[i++];) {
                      UE.dom.domUtils.removeAttributes(btn, ["disabled"]);
                  }
              }
          
              function getLocalData () {
                  alert(UE.getEditor('editor').execCommand( "getlocaldata" ));
              }
          
              function clearLocalData () {
                  UE.getEditor('editor').execCommand( "clearlocaldata" );
                  alert("已清空草稿箱")
              }
          </script>
      </body>
      </html>
      
    • 代码说明

      引入UEditor的库

      <script type="text/javascript" charset="utf-8" src="resource/ueditor/ueditor.config.js"></script>
      <script type="text/javascript" charset="utf-8" src="resource/ueditor/ueditor.all.min.js"> </script>
      <script type="text/javascript" charset="utf-8" src="resource/ueditor/lang/zh-cn/zh-cn.js"></script>
      

      显示编辑器的标签,这个标签跟以往的标签不一样,但是最终的目的也是会生成textarea标签

      <script id="editor" type="text/plain" style="width:1024px;height:500px;"></script>
      

      id很重要,会根据id进行对富文本编辑器的渲染,代码如下

      //实例化编辑器
      var ue = UE.getEditor('editor');
      
      image image

      但是这个时候,图片功能无法使用,需要修改一下配置

      resource/ueditor/jsp/config.json需要修改里面的前缀 /mvc为发布路径

      "imageUrlPrefix": "/mvc",

      "scrawlUrlPrefix": "/mvc",

      "snapscreenUrlPrefix": "/mvc",

      "catcherUrlPrefix": "/mvc",

      "videoUrlPrefix": "/mvc",

      "fileUrlPrefix": "/mvc",

      "imageManagerUrlPrefix": "/mvc",

      "fileManagerUrlPrefix": "/mvc",

      image

4.自定义风格

  • 定制工具栏图标

    请参考官方文档: http://fex.baidu.com/ueditor/#start-toolbar

    <div>
      <h1>完整demo</h1>
      <script id="editor" type="text/plain" style="width:1024px;height:500px;"></script>
    </div>
    
    <script type="text/javascript">
      //实例化编辑器
      var ue = UE.getEditor('editor',{
        toolbars: [
          ['blockquote', 'bold','italic','underline','|', 'strikethrough','subscript','fontborder', 'superscript','|','justifyleft','justifyright', 'justifycenter','justifyjustify','spechars','emotion' ],
          ['insertcode','fontfamily','fontsize','forecolor','backcolor','|','simpleupload','insertimage',]
        ]
      });
    </script>
    
    image
  • 其他配置说明

    autoHeightEnabled {Boolean} [默认值:true] //是否自动长高,默认true

    autoFloatEnabled [默认值:true] //是否保持toolbar的位置不动,默认true

    initialContent {String} [默认值:'欢迎使用ueditor!'] //初始化编辑器的内容,

    initialFrameWidth {Number} [默认值:1000] //初始化编辑器宽度,默认1000

    initialFrameHeight {Number} [默认值:320] //初始化编辑器高度,默认320

    参考网址: http://fex.baidu.com/ueditor/#start-config

      <div>
          <h1>完整demo</h1>
          <script id="editor" type="text/plain" ></script>
      </div>
      
      <script type="text/javascript">
          //实例化编辑器
          var ue = UE.getEditor('editor',{
              toolbars: [
                  ['blockquote', 'bold','italic','underline','|', 'strikethrough','subscript','fontborder', 'superscript','|','justifyleft','justifyright', 'justifycenter','justifyjustify','spechars','emotion' ],
                  ['insertcode','fontfamily','fontsize','forecolor','backcolor','|','simpleupload','insertimage',]
              ],
              autoHeightEnabled:false,
              initialContent:"胖先森带你学习",
              initialFrameWidth:700,
              initialFrameHeight:400
          });
      </script>
    

5.代码高亮显示

JSP页面设置提交表单

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
    //项目的发布路径,例如:  /rabc
    String path = request.getContextPath();
    /*
    全路径,形式如下: http://127.0.0.1:8001/rbac/
    request.getScheme()      ——> http 获取协议
    request.getServerName()  --> 127.0.0.1 获取服务名
    request.getServerPort()  --> 8001 获取端口号
    path                     --> /rbac 获取访问的路径 路
    */
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML>
<html>
    <head>
        <base href="<%=basePath%>">
        <meta charset="UTF-8">
        <title>H5模版:</title>
        <script type="text/javascript" charset="utf-8" src="resource/ueditor/ueditor.config.js"></script>
        <script type="text/javascript" charset="utf-8" src="resource/ueditor/ueditor.all.min.js"> </script>
        <!--建议手动加在语言,避免在ie下有时因为加载语言失败导致编辑器加载失败-->
        <!--这里加载的语言文件会覆盖你在配置项目里添加的语言类型,比如你在配置项目里配置的是英文,这里加载的中文,那最后就是中文-->
        <script type="text/javascript" charset="utf-8" src="resource/ueditor/lang/zh-cn/zh-cn.js"></script>
        <style type="text/css">
            div{
                width:100%;
            }
        </style>
</head>
<body>
    <form action="add" method="post">
    <div>
        <h1>完整demo</h1>
        <script id="editor" type="text/plain" name="content" ></script>
    </div>
    <button>提交数据显示高亮显示</button>
    </form>
    
    
    <script type="text/javascript">
        //实例化编辑器
        var ue = UE.getEditor('editor',{
            toolbars: [
                ['blockquote', 'bold','italic','underline','|', 'strikethrough','subscript','fontborder', 'superscript','|','justifyleft','justifyright', 'justifycenter','justifyjustify','spechars','emotion' ],
                ['insertcode','fontfamily','fontsize','forecolor','backcolor','|','simpleupload','insertimage',]
            ],
            autoHeightEnabled:false,
            initialContent:"胖先森带你学习",
            initialFrameWidth:700,
            initialFrameHeight:400
        });
    </script>
</body>
</html>

Controller获取数据

@Controller
public class TestController {

    @GetMapping("/show")
    public String showUE(){
        return "jsp/ueditor";
    }

    @PostMapping("/add")
    public String add(String content,Model model){
        model.addAttribute("content", content);
        return "jsp/show";
    }
}

show.jsp显示高亮的代码

引入高亮显示的css和js库,渲染

<html>
    <head>
        <base href="<%=basePath%>">
        <meta charset="UTF-8">
        <title>H5模版:</title>
        <link href="resource/ueditor/third-party/SyntaxHighlighter/shCoreDefault.css" rel="stylesheet" type="text/css" />
        <script type="text/javascript" src="resource/ueditor/third-party/SyntaxHighlighter/shCore.js"></script>
    </head>
    <body>
        <p>
          ${content }
        </p>
    <script type="text/javascript">
    SyntaxHighlighter.all();
    </script>
    </body>
</html>
image

备注修改了controller.jsp,需要注意工作空间和tomcat中不能含有中文,否则在线管理不好用

<%@ page language="java" contentType="text/html; charset=UTF-8"
    import="com.baidu.ueditor.ActionEnter"
    pageEncoding="UTF-8"%>
<%@ page trimDirectiveWhitespaces="true" %>
<%

    request.setCharacterEncoding( "utf-8" );
    response.setHeader("Content-Type" , "text/html");
    
    String rootPath = application.getRealPath( "/" );
    String action = request.getParameter("action"); 
    String result = new ActionEnter( request, rootPath ).exec() ;
    
    if( action!=null && (action.equals("listfile") || action.equals("listimage") ) ){  
                rootPath = rootPath.replace("\\", "/");  
                System.out.println("rootPath:"+rootPath);
                result = result.replaceAll(rootPath, "/");  
                System.out.println("result:"+result);
    }  
    out.write( result );
    
%>

相关文章

  • 010.UEditor文档

    UEditor的简单使用 在Java Web阶段和SSM框架阶段,我们的课程设计中都会使用到富文本编辑器,目前流行...

  • 2019-04-26

    测试文档测试文档测试文档测试文档测试文档测试文档测试文档测试文档测试文档测试文档测试文档测试文档测试文档测试文档测...

  • Elasticsearch(ES)文档的CRUD

    新增文档(不指定文档ID) 新增文档(指定文档ID) 通过文档ID获取文档 通过文档ID更新文档 通过文档ID删除...

  • elasticsearch cat api

    健康: 文档 count: 文档 索引:文档 节点:文档 cluster:文档 分片:文档(需要注意state字段)

  • 2020-09-22

    互联网/软件全套文档、产品文档、技术文档、测试文档、运维文档、项目文档 前言简约文档可提高团队沟通效率;详细文档体...

  • Elasticsearch 7.x 入门之restful请求(2

    使用restful操作 创建文档新建文档.png 查看文档文档信息.png 删除文档文档删除.png 新建文档自动...

  • Shape/GradientLayer

    参考文档1参考文档2参考文档3参考文档4参考文档5参考文档6 CAShapeLayer CAShapeLayer ...

  • 文档结构

    项目文档结构 UI文档结构 通用组件文档结构 业务组件文档结构 store文档结构

  • Masonry

    参考文档0参考文档1参考文档2参考文档3参考文档4参考文档5参考文档6 Maonry 代码约束使用比较简单,是对系...

  • HTML常用标签介绍

    HTML文档标签 定义文档类型 定义HTML文档 定义文档头部 定义文档主体 布局标签(包含...

网友评论

    本文标题:010.UEditor文档

    本文链接:https://www.haomeiwen.com/subject/fejjbxtx.html