UEditor的簡單使用
在Java Web階段和SSM框架階段,我們的課程設計中都會使用到富文本編輯器,目前流行的編輯器很多
KindEditor/CKEditor/UEditor/WangEditor等,這里我們使用的是百度開源的,這里我們使用JSP的版本
這部分屬于自學內容,請各位同學根據文檔完成下面配置過程
1.下載UEditor
網址: http://ueditor.baidu.com/website/download.html
2.新建動態的Web項目
因為我使用的是SpringMVC框架,如果使用Java Web階段是比較簡單的.
請注意要排除靜態資源
<!-- 4.1 靜態資源排除方案1 -->
<mvc:default-servlet-handler default-servlet-name="default"/>
將下載的文檔解壓后,復制到WebContent的resource文件夾下,如圖所示:
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');
imageimage但是這個時候,圖片功能無法使用,需要修改一下配置
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>
備注修改了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 );
%>