富編輯模塊可以實現在線文檔編輯功能,並動態上傳插入image/falsh到文檔中。本項目中,我們使用FCKeditor---著名的開源富編輯模塊。要在我們的netjavaWeb項目中使用它,需要如下幾步:
1.下載FCK模塊:
首先,登陸http://www.fckeditor.net/ 下載FCKeditor的版本 FCKeditor_2.6.5.zip,及相關的jar包。
2.項目準備工作:
1.新建WEB工程netjavaFCKTest,將FCKeditor_2.6.5包中的fckeditor文件夾拷貝到項目的WEBContent文件夾下新。
2.將FCKeditor-Java-2.4.2-bin.zip 包中的fckeditor-java-core-2.4.2.jar、commons-fileupload-1.2.1.jar、commons-io-1.3.2.jar 以及slf4j-1.5.8.zip包中的slf4j-api-1.5.8.jar、slf4j-simple-1.5.8.jar文件拷貝到項目的 WebContent/WEB-INF/lib 目錄
3.FCK配置:
1.調用FCK的方式:
1.通過JavaScript調用
內聯方法(首選):在網頁內設置編輯器
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <title>Insert title here</title>
- <!-- 第一件事要做的是將fckeditor.js集成到頁面的<HEAD>就像這樣: -->
- <script type="text/javascript" src="fckeditor/fckeditor.js"></script>
- </head>
- <body>
- <script type="text/javascript">
- //新建一個FCK實例
- var oFCKeditor = new FCKeditor('FCKeditor1');
- //設計編輯器的文件的路徑
- oFCKeditor.BasePath = "/FCKProject2.6.5/fckeditor/";
- //創建並輸出一個編輯器
- oFCKeditor.Create();
- </script>
- </body>
- </html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<!-- 第一件事要做的是將fckeditor.js集成到頁面的<HEAD>就像這樣: -->
<script type="text/javascript" src="fckeditor/fckeditor.js"></script>
</head>
<body>
<script type="text/javascript">
//新建一個FCK實例
var oFCKeditor = new FCKeditor('FCKeditor1');
//設計編輯器的文件的路徑
oFCKeditor.BasePath = "/FCKProject2.6.5/fckeditor/";
//創建並輸出一個編輯器
oFCKeditor.Create();
</script>
</body>
</html>
Textarea的替代方法:在<head>中添加“onload”方法:
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
- <title>Insert title here</title>
- <!-- 第一件事要做的是將fckeditor.js集成到頁面的<HEAD>就像這樣: -->
- <script type="text/javascript" src="fckeditor/fckeditor.js"></script>
- <!-- 第二件事要做的是創建一個onload方法就像這樣: -->
- <script type="text/javascript">
- window.onload = function(){
- var oFCKeditor = new FCKeditor( 'MyTextarea' ) ;
- oFCKeditor.BasePath = "/FCKProject2.6.5/fckeditor/" ;
- oFCKeditor.ReplaceTextarea() ;
- }
- </script>
- </head>
- <body>
- <!-- Body部分添加如下代碼: -->
- <textarea id="MyTextarea" name="MyTextarea"></textarea>
- </body>
- </html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
<!-- 第一件事要做的是將fckeditor.js集成到頁面的<HEAD>就像這樣: -->
<script type="text/javascript" src="fckeditor/fckeditor.js"></script>
<!-- 第二件事要做的是創建一個onload方法就像這樣: -->
<script type="text/javascript">
window.onload = function(){
var oFCKeditor = new FCKeditor( 'MyTextarea' ) ;
oFCKeditor.BasePath = "/FCKProject2.6.5/fckeditor/" ;
oFCKeditor.ReplaceTextarea() ;
}
</script>
</head>
<body>
<!-- Body部分添加如下代碼: -->
<textarea id="MyTextarea" name="MyTextarea"></textarea>
</body>
</html>
FCK屬性:
屬性名 | 描述 | 默認值 |
Windth | 寬度 | 100% |
Height | 高度 | 200 |
Value | 編輯器初始化內容 | (空字符串) |
ToolbarSet | 工具條集合的名稱 | (Default)[內置有default和basic,也可以自定義] |
BasePath | 編輯器的基本路徑 | /fckeditor/ |
FCK構造方法:
Var FCKeditor = function(instanceName,width,height,toolbarSet,value);
instanceName爲編輯器輸出的textarea元素的name屬性的值,必須指定參數會賦值給同名屬性
2.JSP中自定義標籤調用
在JSP中通過自定義標籤調用FCKeditor:
- <%@ page language="java" contentType="text/html; charset=UTF-8"
- pageEncoding="UTF-8"%>
- <!-- 步驟1: 導入自定義標籤庫 -->
- <%@ taglib uri="http://java.fckeditor.net" prefix="FCK" %>
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html><head>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <title>Insert title here</title>
- </head><body>
- <!-- 步驟2: 在Body部分添加FCK標籤: -->
- <FCK:editor instanceName="EditorDefault" toolbarSet="Basic" width="50%" height="400" value="this is my test">
- </FCK:editor>
- </body></html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!-- 步驟1: 導入自定義標籤庫 -->
<%@ taglib uri="http://java.fckeditor.net" prefix="FCK" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head><body>
<!-- 步驟2: 在Body部分添加FCK標籤: -->
<FCK:editor instanceName="EditorDefault" toolbarSet="Basic" width="50%" height="400" value="this is my test">
</FCK:editor>
</body></html>
2. 配置FCKedirot Myconfig.js
方法1:找到FCK主配置文件fckconfig.js,修改FCK的屬性,此文件可以直接修改,一般不建議使用。
方法2:有一個更好的方法有同樣的結果如上所述,但沒有接觸fckconfig.js文件;可以設置自定義配置的路徑,直接在頁面編輯器使用。
這是一個例子,在JavaScript中實現的:
1.建立一個配置文件myconfig.js
(1).修改主配置文件fckconfig.js
- FCKConfig.CustomConfigurationsPath = '/myconfig.js' ;
FCKConfig.CustomConfigurationsPath = '/myconfig.js' ;
(2).建立一個獨立的配置文件,只需要寫修改的配置項 myconfig.js
(3).在調用FCKeditor的時候使用:
- var oFCKeditor = new FCKeditor( "FCKeditor1" ) ;
- oFCKeditor.Config["CustomConfigurationsPath"] = "/myconfig.js" ;
- oFCKeditor.Create() ;
var oFCKeditor = new FCKeditor( "FCKeditor1" ) ;
oFCKeditor.Config["CustomConfigurationsPath"] = "/myconfig.js" ;
oFCKeditor.Create() ;
配置加載順序
1.加載主配置文件fckeditor.js
2.加載自定義的配置文件(如果有),覆蓋相同的配置項
3.使用對實例的配置覆蓋相同的配置項(只對當前實例有效)
提示:
1.系統會自動檢測並運行適當的界面語言(默認,可以修改)
2.不能刪除主配置文件fckconfig.js
3.修改配置後腰清空瀏覽器緩存,以免影響結果(或訪問時強制刷新也可以)
添加一個數字或時間在自定義配置路徑的結尾代碼,強迫瀏覽器每次加載它:
- var oFCKeditor = new FCKeditor( "FCKeditor1" ) ;
- oFCKeditor.Config["CustomConfigurationsPath"] = "/myconfig.js?" + ( new Date() * 1 ) ;
- oFCKeditor.Create() ;
var oFCKeditor = new FCKeditor( "FCKeditor1" ) ;
oFCKeditor.Config["CustomConfigurationsPath"] = "/myconfig.js?" + ( new Date() * 1 ) ;
oFCKeditor.Create() ;
3.需要修改的配置
1.自定義ToolbarSet,去掉一些功能
2.加上幾種常用的字體
3.修改"回車"和"Shift+回車"的換行行爲( 默認的回車是一個段落)
4.修改編輯區樣式文件 @import url(路徑);
5.更換表情圖片
注意:
1.要使用UTF-8編碼保存配置文件
2.FCKConfig.BasePath和調用fckeditor時指定的
BasePath(FCKeditor.BasePath)不是同一個,其值也不一樣
- //設置語言,是否自動檢測,默認爲TRUE,此處設置爲不自動檢測,會覆蓋默認的設置
- FCKConfig.AutoDetectLanguage = true ;
- //自定義ToolbarSet,去掉一些功能
- FCKConfig.ToolbarSets["NetJava"] = [
- ['Bold','Italic','Underline','StrikeThrough','-','Subscript','Superscript'],
- ['OrderedList','UnorderedList','-','Outdent','Indent','Blockquote','CreateDiv'],
- ['JustifyLeft','JustifyCenter','JustifyRight','JustifyFull'],
- ['Link','Unlink','Anchor'],
- ['Image','Flash','Table','Rule','Smiley','SpecialChar','PageBreak'],
- '/',
- ['Style','FontFormat','FontName','FontSize'],
- ['TextColor','BGColor'],
- ['FitWindow','ShowBlocks','-','About'] // No comma for the last row.
- ] ;
- //修改字體,加上中文的字體
- FCKConfig.FontNames = '黑體;Arial;Comic Sans MS;Courier New;Tahoma;Times New Roman;Verdana' ;
- //修改"回車"和"Shift+回車"的換行行爲( 默認的回車是一個段落)
- FCKConfig.EnterMode = 'br' ; // p | div | br
- FCKConfig.ShiftEnterMode = 'p' ; // p | div | br
- //修改編輯區樣式文件 ,在fck_editorarea.css中使用@import url(路徑)
- FCKConfig.EditorAreaCSS = FCKConfig.BasePath + 'css/fck_editorarea.css' ;
- //更換表情圖片;表情圖片的位置
- FCKConfig.SmileyPath = FCKConfig.BasePath + 'images/smiley/wangwang/' ;
- //要顯示的表情圖片的名字
- FCKConfig.SmileyImages = ['001.gif','002.gif','003.gif','004.gif','005.gif','006.gif','007.gif','008.gif','009.gif','010.gif','011.gif','012.gif','013.gif','014.gif','015.gif','016.gif','017.gif','018.gif','019.gif','020.gif','021.gif','022.gif','023.gif','024.gif','025.gif','026.gif','027.gif','028.gif','029.gif','030.gif'] ;
- //每行顯示多少個表情圖片
- FCKConfig.SmileyColumns = 5 ;
- //顯示錶情圖片的寬度
- FCKConfig.SmileyWindowWidth = 435 ;
- //顯示錶情圖片的高度
- FCKConfig.SmileyWindowHeight = 210 ;
//設置語言,是否自動檢測,默認爲TRUE,此處設置爲不自動檢測,會覆蓋默認的設置
FCKConfig.AutoDetectLanguage = true ;
//自定義ToolbarSet,去掉一些功能
FCKConfig.ToolbarSets["NetJava"] = [
['Bold','Italic','Underline','StrikeThrough','-','Subscript','Superscript'],
['OrderedList','UnorderedList','-','Outdent','Indent','Blockquote','CreateDiv'],
['JustifyLeft','JustifyCenter','JustifyRight','JustifyFull'],
['Link','Unlink','Anchor'],
['Image','Flash','Table','Rule','Smiley','SpecialChar','PageBreak'],
'/',
['Style','FontFormat','FontName','FontSize'],
['TextColor','BGColor'],
['FitWindow','ShowBlocks','-','About'] // No comma for the last row.
] ;
//修改字體,加上中文的字體
FCKConfig.FontNames = '黑體;Arial;Comic Sans MS;Courier New;Tahoma;Times New Roman;Verdana' ;
//修改"回車"和"Shift+回車"的換行行爲( 默認的回車是一個段落)
FCKConfig.EnterMode = 'br' ; // p | div | br
FCKConfig.ShiftEnterMode = 'p' ; // p | div | br
//修改編輯區樣式文件 ,在fck_editorarea.css中使用@import url(路徑)
FCKConfig.EditorAreaCSS = FCKConfig.BasePath + 'css/fck_editorarea.css' ;
//更換表情圖片;表情圖片的位置
FCKConfig.SmileyPath = FCKConfig.BasePath + 'images/smiley/wangwang/' ;
//要顯示的表情圖片的名字
FCKConfig.SmileyImages = ['001.gif','002.gif','003.gif','004.gif','005.gif','006.gif','007.gif','008.gif','009.gif','010.gif','011.gif','012.gif','013.gif','014.gif','015.gif','016.gif','017.gif','018.gif','019.gif','020.gif','021.gif','022.gif','023.gif','024.gif','025.gif','026.gif','027.gif','028.gif','029.gif','030.gif'] ;
//每行顯示多少個表情圖片
FCKConfig.SmileyColumns = 5 ;
//顯示錶情圖片的寬度
FCKConfig.SmileyWindowWidth = 435 ;
//顯示錶情圖片的高度
FCKConfig.SmileyWindowHeight = 210 ;
4.文件上傳
需求:
1.文件名爲中文的文件時會出現亂碼
2.創建中文目錄名會出現亂碼
3.引用中文名的圖片不能正常顯示
1.修改web.XML中的配置
- <servlet>
- <servlet-name>ConnectorServlet</servlet-name>
- <servlet-class>
- cn.netjava.fckeditor.ConnectorServlet
- </servlet-class>
- <load-on-startup>1</load-on-startup>
- </servlet>
- <servlet-mapping>
- <servlet-name>ConnectorServlet</servlet-name>
- <url-pattern>
- /fckeditor/editor/filemanager/connectors/*
- </url-pattern>
- </servlet-mapping>
<servlet>
<servlet-name>ConnectorServlet</servlet-name>
<servlet-class>
cn.netjava.fckeditor.ConnectorServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>ConnectorServlet</servlet-name>
<url-pattern>
/fckeditor/editor/filemanager/connectors/*
</url-pattern>
</servlet-mapping>
2.重寫FCK的ConnectorServlet文件
1.文件名爲中文的文件時會出現亂碼
在ConnectorServlet類的doPost方法中加上粗體部分代碼。
- //……
- if (!currentDir.exists())
- ur = UploadResponse.UR_INVALID_CURRENT_FOLDER;
- else {
- String newFilename = null;
- FileItemFactory factory = new DiskFileItemFactory();
- ServletFileUpload upload = new ServletFileUpload(factory);
- //設置編碼爲UTF-8
- upload.setHeaderEncoding("UTF-8");
- try {
- //……
//……
if (!currentDir.exists())
ur = UploadResponse.UR_INVALID_CURRENT_FOLDER;
else {
String newFilename = null;
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
//設置編碼爲UTF-8
upload.setHeaderEncoding("UTF-8");
try {
//……
2.創建中文目錄名會出現亂碼
在ConnectorServlet類的doGet方法中加上粗體部分代碼。
- //……
- else if (command.equals(CommandHandler.CREATE_FOLDER)) {
- //取得要建立的文件夾的名字
- String strFileName = request.getParameter("NewFolderName");
- //進行編碼轉換
- strFileName = new String(strFileName.getBytes("iso8859-1"),"UTF-8");
- String newFolderStr = UtilsFile.sanitizeFolderName(strFileName);
- logger.debug("Parameter NewFolderName: {}", newFolderStr);
- //……
//……
else if (command.equals(CommandHandler.CREATE_FOLDER)) {
//取得要建立的文件夾的名字
String strFileName = request.getParameter("NewFolderName");
//進行編碼轉換
strFileName = new String(strFileName.getBytes("iso8859-1"),"UTF-8");
String newFolderStr = UtilsFile.sanitizeFolderName(strFileName);
logger.debug("Parameter NewFolderName: {}", newFolderStr);
//……
3.引用中文名的圖片不能正常顯示
(1).修改tomcat連接器的配置URIEncoding(建議不要使用,這個方法對Get方法進行的提交會對中文進行解碼,有可能會產生亂碼)。
原因是:圖片引用的地址進行URL編碼,當使用這個路徑訪問服務器時,先進行解碼,這樣就會解釋成亂碼,所以找不到對應的資源。
- <Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" URIEncoding="UTF-8"/>
<Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" URIEncoding="UTF-8"/>
(2).避免出現引用中文名字圖片的情況,在ConnectorServlet類的doPost方法中加上粗體部分代碼。
- //……
- FileItem uplFile = items.get(0);
- String rawName = UtilsFile.sanitizeFileName(uplFile.getName());
- String filename = FilenameUtils.getName(rawName);
- String baseName = FilenameUtils.removeExtension(filename);
- String extension = FilenameUtils.getExtension(filename);
- //使用UUID來替換文件名
- filename = UUID.randomUUID().toString() + "." + extension;
- //如果文件擴展名不允許上傳
- if (!ExtensionsHandler.isAllowed(resourceType, extension))
- //……
//……
FileItem uplFile = items.get(0);
String rawName = UtilsFile.sanitizeFileName(uplFile.getName());
String filename = FilenameUtils.getName(rawName);
String baseName = FilenameUtils.removeExtension(filename);
String extension = FilenameUtils.getExtension(filename);
//使用UUID來替換文件名
filename = UUID.randomUUID().toString() + "." + extension;
//如果文件擴展名不允許上傳
if (!ExtensionsHandler.isAllowed(resourceType, extension))
//……
4. 控制上傳文件的大小和自定義錯誤碼
1.在上傳文件的頁面(瀏覽器)加載文件點擊“Upload”按鈕,將表單提交到ConnectorServlet(服務器),ConnectorServlet處理上傳的文件(不同的處理結果對應不同的響應消息),ConnectorServlet通過處理的結果調用不同的回調函數,並傳遞錯誤碼,對錯誤碼進行處理。
打印錯誤碼對應的提示信息步驟:
1.在服務器端的Servlet中,在保存文件之前先判斷文件的大小,如果超出限制,就傳遞一個自定義的錯誤碼,並且不再保存文件。在ConnectorServlet類的doPost方法中加上粗體部分代碼。
- //……
- //如果文件擴展名不允許上傳
- if (!ExtensionsHandler.isAllowed(resourceType, extension))
- ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION);
- //如果文件大小超出限制
- else if(uplFile.getSize() > 100 * 1024){
- //傳遞一個自定義的錯誤碼
- ur = new UploadResponse(204);
- }
- //如果不存在以上情況,則保存文件
- else {
- //……
//……
//如果文件擴展名不允許上傳
if (!ExtensionsHandler.isAllowed(resourceType, extension))
ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION);
//如果文件大小超出限制
else if(uplFile.getSize() > 100 * 1024){
//傳遞一個自定義的錯誤碼
ur = new UploadResponse(204);
}
//如果不存在以上情況,則保存文件
else {
//……
2.修改對應的頁面中的回調函數,增加對這個自定義的錯誤碼的處理。在WebContenteditordialogfck_image文件夾下Fck_image.js文件中加上粗體部分代碼。
- switch ( errorNumber ){
- case 0 : // No errors
- alert( 'Your file has been successfully uploaded' ) ;
- break ;
- case 1 : // Custom error
- alert( customMsg ) ;
- return ;
- case 101 : // Custom warning
- alert( customMsg ) ;
- break ;
- case 201 :
- alert( 'A file with the same name is already available. The uploaded file has been renamed to "' + fileName + '"' ) ;
- break ;
- case 202 :
- alert( 'Invalid file type' ) ;
- return ;
- case 203 :
- alert( "Security error. You probably don't have enough permissions to upload. Please check your server." ) ;
- return ;
- //將ConnectorServlet文件中自定義的204錯誤碼在此處進行定義。
- case 204 :
- alert( "文件大小超出限制" ) ;
- return ;
- case 500 :
- alert( 'The connector is disabled' ) ;
- break ;
- default :
- alert( 'Error on file upload. Error number: ' + errorNumber ) ;
- return ;
- }
switch ( errorNumber ){
case 0 : // No errors
alert( 'Your file has been successfully uploaded' ) ;
break ;
case 1 : // Custom error
alert( customMsg ) ;
return ;
case 101 : // Custom warning
alert( customMsg ) ;
break ;
case 201 :
alert( 'A file with the same name is already available. The uploaded file has been renamed to "' + fileName + '"' ) ;
break ;
case 202 :
alert( 'Invalid file type' ) ;
return ;
case 203 :
alert( "Security error. You probably don't have enough permissions to upload. Please check your server." ) ;
return ;
//將ConnectorServlet文件中自定義的204錯誤碼在此處進行定義。
case 204 :
alert( "文件大小超出限制" ) ;
return ;
case 500 :
alert( 'The connector is disabled' ) ;
break ;
default :
alert( 'Error on file upload. Error number: ' + errorNumber ) ;
return ;
}