在線編輯器最好的當然是CKEditor.本文介紹CKEditor在jsp環境下的使用。(至少JRE 1.4 and Servlet 2.5/JSP 2.1)
下載 http://ckeditor.com/download,推薦下載 ckeditor-java-3.6.4,關鍵的包是 ckeditor-java-core-3.x.y.jar,x,y表示版本號。目前最新是3.5.3。解壓後把ckeditor放入你的工程目錄,(當然你可以刪除其中像_samples等無實際意義的文件夾);把 ckeditor-core.jar放入工程類加載目錄(lib\)。
在Jsp文件導入必要包,
<%@page import="com.ckeditor.CKEditorConfig"%>
<%@page import="com.ckeditor.EventHandler"%>
標籤引入,
<%@ taglib uri="http://ckeditor.com" prefix="ckeditor" %>
下面是例子,
<html>
<body>
<form action="getEditor.jsp" method="post">
<p>
<label for="editor1">Editor 1:</label>
<textarea cols="80" id="editor1" name="editor1" rows="10"></textarea>
</p>
<p>
<input type="submit" value="Submit" />
</p>
</form>
<%
CKEditorConfig settings = new CKEditorConfig();
// settings.addConfigValue("toolbar","[[ 'Source', '-', 'Bold', 'Italic' ]]");
%>
<ckeditor:replace replace="editor1" basePath="ckeditor/" />
</body>
</html>
核心是利用ckeditor標籤replace一個textarea。你也可以進行各種定製,比如定義編輯器樣式、工具欄等。
以下介紹如何將CKEditor和CKFinder組合使用,因爲如果不這樣,編輯器上傳圖片等功能是無法使用的。CKFinder的單獨配置這裏不介紹,相關可以查看筆者以前的博客。
組合的方法可以採取taglib的方式,也可以採用Js的方式。
Taglib:
<%@ taglib uri="http://cksource.com/ckfinder" prefix="ckfinder" %>
然後使用:<ckfinder:setupCKEditor basePath="ckfinder/" editor="editor1" />
Js:
var editor = CKEDITOR.replace( 'editor1' );
CKFinder.setupCKEditor( editor, '/ckfinder/' );
當然上述兩種方式都可以進一步自定義設置。效果圖如下: