UEditor的簡單使用
在Java Web階段和SSM框架階段,我們的課程設(shè)計(jì)中都會(huì)使用到富文本編輯器,目前流行的編輯器很多
KindEditor/CKEditor/UEditor/WangEditor等,這里我們使用的是百度開源的,這里我們使用JSP的版本
這部分屬于自學(xué)內(nèi)容,請各位同學(xué)根據(jù)文檔完成下面配置過程
1.下載UEditor
網(wǎng)址: http://ueditor.baidu.com/website/download.html
2.新建動(dòng)態(tài)的Web項(xiàng)目
因?yàn)槲沂褂玫氖荢pringMVC框架,如果使用Java Web階段是比較簡單的.
請注意要排除靜態(tài)資源
<!-- 4.1 靜態(tài)資源排除方案1 -->
<mvc:default-servlet-handler default-servlet-name="default"/>
將下載的文檔解壓后,復(fù)制到WebContent的resource文件夾下,如圖所示:
3.顯示富文本編輯器
-
添加UEditor需要的Jar包
將紅色部分的jar包復(fù)制添加到WEB-INF/lib下
-
顯示富文本編輯器
根據(jù)示例中的index.html或者官方文檔給的示例,將富文本編輯器進(jìn)行顯示,因?yàn)槲覀儗⑺械腏SP都放置到WEB-INF文件夾
-
新建Controller完成跳轉(zhuǎn)
@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> <!--建議手動(dòng)加在語言,避免在ie下有時(shí)因?yàn)榧虞d語言失敗導(dǎo)致編輯器加載失敗--> <!--這里加載的語言文件會(huì)覆蓋你在配置項(xiàng)目里添加的語言類型,比如你在配置項(xiàng)目里配置的是英文堤框,這里加載的中文,那最后就是中文--> <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()">獲得整個(gè)html的內(nèi)容</button> <button onclick="getContent()">獲得內(nèi)容</button> <button onclick="setContent()">寫入內(nèi)容</button> <button onclick="setContent(true)">追加內(nèi)容</button> <button onclick="getContentTxt()">獲得純文本</button> <button onclick="getPlainTxt()">獲得帶格式的純文本</button> <button onclick="hasContent()">判斷是否有內(nèi)容</button> <button onclick="setFocus()">使編輯器獲得焦點(diǎn)</button> <button onmousedown="isFocus(event)">編輯器是否獲得焦點(diǎn)</button> <button onmousedown="setblur(event)" >編輯器失去焦點(diǎn)</button> </div> <div> <button onclick="getText()">獲得當(dāng)前選中的文本</button> <button onclick="insertHtml()">插入給定的內(nèi)容</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)">設(shè)置高度為300默認(rèn)關(guān)閉了自動(dòng)長高</button> </div> <div> <button onclick="getLocalData()" >獲取草稿箱內(nèi)容</button> <button onclick="clearLocalData()" >清空草稿箱</button> </div> </div> <div> <button onclick="createEditor()"> 創(chuàng)建編輯器</button> <button onclick="deleteEditor()"> 刪除編輯器</button> </div> <script type="text/javascript"> //實(shí)例化編輯器 //建議使用工廠方法getEditor創(chuàng)建和引用編輯器實(shí)例葫男,如果在某個(gè)閉包下引用該編輯器,直接調(diào)用UE.getEditor('editor')就能拿到相關(guān)的實(shí)例 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()方法可以獲得編輯器的內(nèi)容"); arr.push("內(nèi)容為:"); arr.push(UE.getEditor('editor').getContent()); alert(arr.join("\n")); } function getPlainTxt() { var arr = []; arr.push("使用editor.getPlainTxt()方法可以獲得編輯器的帶格式的純文本內(nèi)容"); arr.push("內(nèi)容為:"); arr.push(UE.getEditor('editor').getPlainTxt()); alert(arr.join('\n')) } function setContent(isAppendTo) { var arr = []; arr.push("使用editor.setContent('歡迎使用ueditor')方法可以設(shè)置編輯器的內(nèi)容"); 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() { //當(dāng)你點(diǎn)擊按鈕時(shí)編輯區(qū)域已經(jīng)失去了焦點(diǎn),如果直接用getText將不會(huì)得到內(nèi)容袭祟,所以要在選回來遏插,然后取得內(nèi)容 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()方法可以獲得編輯器的純文本內(nèi)容"); arr.push("編輯器的純文本內(nèi)容為:"); arr.push(UE.getEditor('editor').getContentTxt()); alert(arr.join("\n")); } function hasContent() { var arr = []; arr.push("使用editor.hasContents()方法判斷編輯器里是否有內(nèi)容"); arr.push("判斷結(jié)果為:"); 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>
-
代碼說明
引入U(xiǎn)Editor的庫
<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>
顯示編輯器的標(biāo)簽,這個(gè)標(biāo)簽跟以往的標(biāo)簽不一樣,但是最終的目的也是會(huì)生成textarea標(biāo)簽
<script id="editor" type="text/plain" style="width:1024px;height:500px;"></script>
id很重要,會(huì)根據(jù)id進(jìn)行對富文本編輯器的渲染,代碼如下
//實(shí)例化編輯器 var ue = UE.getEditor('editor');
但是這個(gè)時(shí)候,圖片功能無法使用,需要修改一下配置
resource/ueditor/jsp/config.json需要修改里面的前綴 /mvc為發(fā)布路徑
"imageUrlPrefix": "/mvc",
"scrawlUrlPrefix": "/mvc",
"snapscreenUrlPrefix": "/mvc",
"catcherUrlPrefix": "/mvc",
"videoUrlPrefix": "/mvc",
"fileUrlPrefix": "/mvc",
"imageManagerUrlPrefix": "/mvc",
"fileManagerUrlPrefix": "/mvc",
-
4.自定義風(fēng)格
-
定制工具欄圖標(biāo)
請參考官方文檔: 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"> //實(shí)例化編輯器 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>
-
其他配置說明
autoHeightEnabled {Boolean} [默認(rèn)值:true] //是否自動(dòng)長高捂贿,默認(rèn)true
autoFloatEnabled [默認(rèn)值:true] //是否保持toolbar的位置不動(dòng),默認(rèn)true
initialContent {String} [默認(rèn)值:'歡迎使用ueditor!'] //初始化編輯器的內(nèi)容胳嘲,
initialFrameWidth {Number} [默認(rèn)值:1000] //初始化編輯器寬度厂僧,默認(rèn)1000
initialFrameHeight {Number} [默認(rèn)值:320] //初始化編輯器高度,默認(rèn)320
參考網(wǎng)址: http://fex.baidu.com/ueditor/#start-config
<div> <h1>完整demo</h1> <script id="editor" type="text/plain" ></script> </div> <script type="text/javascript"> //實(shí)例化編輯器 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:"胖先森帶你學(xué)習(xí)", initialFrameWidth:700, initialFrameHeight:400 }); </script>
5.代碼高亮顯示
JSP頁面設(shè)置提交表單
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
//項(xiàng)目的發(fā)布路徑了牛,例如: /rabc
String path = request.getContextPath();
/*
全路徑颜屠,形式如下: http://127.0.0.1:8001/rbac/
request.getScheme() ——> http 獲取協(xié)議
request.getServerName() --> 127.0.0.1 獲取服務(wù)名
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>
<!--建議手動(dòng)加在語言,避免在ie下有時(shí)因?yàn)榧虞d語言失敗導(dǎo)致編輯器加載失敗-->
<!--這里加載的語言文件會(huì)覆蓋你在配置項(xiàng)目里添加的語言類型白魂,比如你在配置項(xiàng)目里配置的是英文汽纤,這里加載的中文,那最后就是中文-->
<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>提交數(shù)據(jù)顯示高亮顯示</button>
</form>
<script type="text/javascript">
//實(shí)例化編輯器
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:"胖先森帶你學(xué)習(xí)",
initialFrameWidth:700,
initialFrameHeight:400
});
</script>
</body>
</html>
Controller獲取數(shù)據(jù)
@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 );
%>