010.UEditor文檔

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 );
    
%>
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 230,622評論 6 544
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 99,716評論 3 429
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 178,746評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,991評論 1 318
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,706評論 6 413
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 56,036評論 1 329
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 44,029評論 3 450
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 43,203評論 0 290
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,725評論 1 336
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,451評論 3 361
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,677評論 1 374
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,161評論 5 365
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,857評論 3 351
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,266評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,606評論 1 295
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,407評論 3 400
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,643評論 2 380

推薦閱讀更多精彩內容

  • 文章分類 后臺文章分類列表頁模板導的詳細步驟建立數據表blog_category,并添加相應的文章字段使用php ...
    JoyceZhao閱讀 1,750評論 0 14
  • @轉自GitHub 介紹js的基本數據類型。Undefined、Null、Boolean、Number、Strin...
    YT_Zou閱讀 1,184評論 0 0
  • 以下是常用的代碼收集,學習用。轉自豪情博客園 1. PC - js 返回指定范圍的隨機數(m-n之間)的公式 re...
    自由加咖啡閱讀 1,014評論 0 1
  • 1.背景介紹 在做Web應用時,經常會進行富文本編輯,常用的富文本編輯器有很多,比如CuteEditor、CKEd...
    維克拉瑪蒂亞閱讀 2,237評論 0 0
  • 文、畫/云塵 首先,不管你是創作還是臨摹,尋找素材都是有必要的。哪怕你只是畫個蘋果,也是可以嚴謹的去找張素材來參照...
    云影拂塵閱讀 843評論 28 38