struts2中富文本编辑器使用ckeditor和ckfinder,实现富文本编辑

来源:互联网 发布:暂时纹身 知乎 编辑:程序博客网 时间:2024/05/08 04:32

struts2中富文本编辑器使用ckeditor和ckfinder,实现富文本编辑

[目录]

1:首先搭建好struts开发环境:

1.1下载struts2jar包,并导入struts2的jar包

1.2在web.xml中配置好struts2的过滤器:

   <filter>        <filter-name>struts2</filter-name>        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>    </filter>    <filter-mapping>        <filter-name>struts2</filter-name>        <url-pattern>*.action</url-pattern>

1.3导入struts2.xml配置文件到src下:

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"    "http://struts.apache.org/dtds/struts-2.3.dtd"><struts>    <constant name="struts.enable.DynamicMethodInvocation" value="false" />    <constant name="struts.devMode" value="true" /><!--     国际化文件开头 -->    <constant name="struts.custom.i18n.resources" value="app"></constant><!--    multipart上传缓存路径 -->    <constant name="struts.multipart.saveDir" value="F:\cache"></constant>    <package name="default" namespace="/" extends="struts-default">    </package></struts>

2:下载ckeditor和ckfinder文件:

2.1ckeditor和ckfinder下载还用各自的java开发jar包:

ckeditor下载:http://ckeditor.com/,选择fullpackage

这里写图片描述
ckfinder下载:https://cksource.com/ckfinder
我这里不提供下载,我的云盘总是失效

2.2,解压ckeditor和ckfinder压缩包,并且导如ckfinde和ckeditor的jar包到项目中:

所有jar包如下,删除sample文件夹:
这里写图片描述

2.3导入ckfinder的文件夹下的config.xml文件到web-inf下:

**并且修改
enabled = true

修改baseurl上传文件的路径
/ckscxz/userfiles/**

<config>    <!--    CKFinder : Configuration File - Basic Instructions    In a generic usage case, the following tasks must be done to configure CKFinder:    1. Check the baseDir and baseUrl options;    2. If available, paste your license key in the "licenseKey" setting;    3. Enable CKFinder using the "enabled" setting.    WARNING : DO NOT simply set "enabled" to "true" on a production site. By doing so, you     are allowing "anyone" to upload and list the files in your server. You must implement    some kind of session validation.    http://docs.cksource.com/CKFinder_2.x/Developers_Guide/Java/Configuration/Extending    -->    <enabled>true</enabled>    <!--    Configure the location of uploaded files. See the following article for more details:    http://docs.cksource.com/CKFinder_2.x/Developers_Guide/Java/Configuration/baseURL_and_baseDir    -->    <baseDir></baseDir>    <baseURL>/CKStruts2/userfiles/</baseURL>    <licenseKey></licenseKey>    <licenseName></licenseName>    <!--    Set the maximum size of uploaded images. If an uploaded image is larger, it    gets scaled down proportionally. Set to 0 to disable this feature.    -->    <imgWidth>1600</imgWidth>    <imgHeight>1200</imgHeight>    <imgQuality>80</imgQuality>    <!--    See the following article for more details:    http://docs.cksource.com/CKFinder_2.x/Developers_Guide/Java/Configuration/URI_Encoding    -->    <uriEncoding>UTF-8</uriEncoding>    <!--    ResourceType : defines the "resource types" handled in CKFinder. A resource    type is nothing more than a way to group files under different paths, each one    having different configuration settings.    Each resource type name must be unique.    When loading CKFinder, the "type" querystring parameter can be used to display    a specific type only. If "type" is omitted in the URL, the    "DefaultResourceTypes" settings is used (may contain the resource type names    separated by a comma). If left empty, all types are loaded.    maxSize is defined in bytes, but shorthand notation may be also used.    Available options are: G, M, K (case insensitive).    1M equals 1048576 bytes (one Megabyte), 1K equals 1024 bytes (one Kilobyte), 1G equals one Gigabyte.    Example: 'maxSize' => "8M",    ==============================================================================    ATTENTION: Flash files with `swf' extension, just like HTML files, can be used     to execute JavaScript code and to e.g. perform an XSS attack. Grant permission     to upload `.swf` files only if you understand and can accept this risk.    ==============================================================================    -->    <defaultResourceTypes></defaultResourceTypes>    <types>        <type name="Files">            <url>%BASE_URL%files/</url>            <directory>%BASE_DIR%files</directory>            <maxSize>0</maxSize>            <allowedExtensions>7z,aiff,asf,avi,bmp,csv,doc,docx,fla,flv,gif,gz,gzip,jpeg,jpg,mid,mov,mp3,mp4,mpc,mpeg,mpg,ods,odt,pdf,png,ppt,pptx,pxd,qt,ram,rar,rm,rmi,rmvb,rtf,sdc,sitd,swf,sxc,sxw,tar,tgz,tif,tiff,txt,vsd,wav,wma,wmv,xls,xlsx,zip            </allowedExtensions>            <deniedExtensions></deniedExtensions>        </type>        <type name="Images">            <url>%BASE_URL%images/</url>            <directory>%BASE_DIR%images</directory>            <maxSize>0</maxSize>            <allowedExtensions>bmp,gif,jpeg,jpg,png</allowedExtensions>            <deniedExtensions></deniedExtensions>        </type>        <type name="Flash">            <url>%BASE_URL%flash/</url>            <directory>%BASE_DIR%flash</directory>            <maxSize>0</maxSize>            <allowedExtensions>swf,flv</allowedExtensions>            <deniedExtensions></deniedExtensions>        </type>    </types>    <!--    The session variable name that CKFinder must use to retrieve    the "role" of the current user. The "role", can be used in the "accessControls"    settings (bellow).    -->    <userRoleSessionVar>CKFinder_UserRole</userRoleSessionVar>    <accessControls>        <accessControl>            <role>*</role>            <resourceType>*</resourceType>            <folder>/</folder>            <folderView>true</folderView>            <folderCreate>true</folderCreate>            <folderRename>true</folderRename>            <folderDelete>true</folderDelete>            <fileView>true</fileView>            <fileUpload>true</fileUpload>            <fileRename>true</fileRename>            <fileDelete>true</fileDelete>        </accessControl>    </accessControls>    <thumbs>        <enabled>true</enabled>        <url>%BASE_URL%_thumbs/</url>        <directory>%BASE_DIR%_thumbs</directory>        <directAccess>false</directAccess>        <maxHeight>100</maxHeight>        <maxWidth>100</maxWidth>        <quality>80</quality>    </thumbs>    <!--    Increases the security on an IIS web server.    If enabled, CKFinder will disallow creating folders and uploading files whose names contain characters     that are not safe under an IIS web server.    -->    <disallowUnsafeCharacters>false</disallowUnsafeCharacters>    <!--    Due to security issues with Apache modules, it is recommended to leave the    following setting enabled.    How does it work? Suppose the following:    - If "php" is on the denied extensions list, a file named foo.php cannot be      uploaded.    - If "rar" (or any other) extension is allowed, one can upload a file named      foo.rar.    - The file foo.php.rar has "rar" extension so, in theory, it can be also      uploaded.    In some conditions Apache can treat the foo.php.rar file just like any PHP    script and execute it.    If CheckDoubleExtension is enabled, each part of the file name after a dot is    checked, not only the last part. In this way, uploading foo.php.rar would be    denied, because "php" is on the denied extensions list.    -->    <checkDoubleExtension>true</checkDoubleExtension>    <!--    Indicates that the file size (maxSize) for images must be checked only    after scaling them. Otherwise, it is checked right after uploading.    -->    <checkSizeAfterScaling>true</checkSizeAfterScaling>    <!--    Perform additional checks for image files    if set to true, validate image size    -->    <secureImageUploads>true</secureImageUploads>    <!--    For security, HTML is allowed in the first Kb of data for files having the    following extensions only.    -->    <htmlExtensions>html,htm,xml,js</htmlExtensions>    <!--    Force ASCII names for files and folders. If enabled, characters with diactric     marks will be automatically converted to ASCII letters.    -->    <forceASCII>false</forceASCII>    <!--    Folders to not display in CKFinder, no matter their location.    No paths are accepted, only the folder name.    The * and ? wildcards are accepted.    ".*" disallows the creation of folders starting with a dot character.    -->    <hideFolders>        <folder>.*</folder>        <folder>CVS</folder>    </hideFolders>    <!--    Files to not display/upload in CKFinder, no matter their location.    No paths are accepted, only the file name, including extension.    The * and ? wildcards are accepted.    -->    <hideFiles>        <file>.*</file>    </hideFiles>    <plugins>        <plugin>            <name>imageresize</name>            <class>com.ckfinder.connector.plugins.ImageResize</class>            <params>                <param name="smallThumb" value="90x90"></param>                <param name="mediumThumb" value="120x120"></param>                <param name="largeThumb" value="180x180"></param>            </params>        </plugin>        <plugin>            <name>fileeditor</name>            <class>com.ckfinder.connector.plugins.FileEditor</class>            <params></params>        </plugin>        <!-- Before enabling the watermark plugin make sure to specify path to source image -->        <!-- The "internal" flag informs CKFinder that watermark is a pure server side plugin -->        <!--        <plugin>            <name>watermark</name>            <class>com.ckfinder.connector.plugins.Watermark</class>            <params>                <param name="source" value="/path/in/servlet/context/logo.gif"></param>                <param name="transparency" value="0.8"></param>                <param name="quality" value="100"></param>                <param name="marginRight" value="5"></param>                <param name="marginBottom" value="5"></param>            </params>            <internal>true</internal>        </plugin>        -->    </plugins>    <basePathBuilderImpl>com.ckfinder.connector.configuration.ConfigurationPathBuilder</basePathBuilderImpl></config>

2.4配置ckeditor:

打开ckeditor文件夹,下的config.js配置如下:

/** * @license Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.html or http://ckeditor.com/license */CKEDITOR.editorConfig = function( config ) {    config.language =  "zh-cn" ; // 配置语言      config.toolbar = 'Full';    config.image_previewText = " ";     config.uiColor = '#FFF'; // 背景颜色      config.image_previewText=''; //预览区域显示内容      //  config.width = 'auto'; // 宽度      config.height = '500px'; // 高度      config.skin = 'office2003';//界面v2,kama,office2003      config.toolbarGroups = [        { name: 'clipboard',   groups: [ 'clipboard', 'undo' ] },        { name: 'editing',     groups: [ 'find', 'selection', 'spellchecker' ] },        { name: 'links' },        { name: 'insert' },        { name: 'forms' },        { name: 'tools' },        { name: 'document',    groups: [ 'mode', 'document', 'doctools' ] },        { name: 'others' },        '/',        { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] },        { name: 'paragraph',   groups: [ 'list', 'indent', 'blocks', 'align', 'bidi' ] },        { name: 'styles' },        { name: 'colors' },        { name: 'about' }    ];    // Remove some buttons provided by the standard plugins, which are    // not needed in the Standard(s) toolbar.    config.removeButtons = 'Underline,Subscript,Superscript';    // Set the most common block elements.    config.format_tags = 'p;h1;h2;h3;pre';    // Simplify the dialog windows.    config.removeDialogTabs = 'image:advanced;link:advanced';    // 在 CKEditor 中集成 CKFinder,注意 ckfinder的路径选择要正确。       config.filebrowserBrowseUrl =  '/CKStruts2/ckfinder/ckfinder.html' ;         config.filebrowserImageBrowseUrl =  '/CKStruts2/ckfinder/ckfinder.html?type=Images' ;         config.filebrowserFlashBrowseUrl =  '/CKStruts2/ckfinder/ckfinder.html?type=Flash' ;         config.filebrowserUploadUrl =  '/CKStruts2/ckfinder/core/connector/java/connector.java?command=QuickUpload&type=Files' ;         config.filebrowserImageUploadUrl =  '/CKStruts2/ckfinder/core/connector/java/connector.java?command=QuickUpload&type=Images' ;         config.filebrowserFlashUploadUrl =  '/CKStruts2/ckfinder/core/connector/java/connector.java?command=QuickUpload&type=Flash' ;         config.filebrowserWindowWidth = '1000';         config.filebrowserWindowHeight = '700';         config.language =  "zh-cn" ;  };

详细配置可参考,官方文档,或者:这篇博客:
http://www.cnblogs.com/Setme/archive/2012/06/05/2536568.html

3:ckfinder和ckeditor的说明文字去除

ckeditor config.js配置    config.language =  "zh-cn" ;     config.image_previewText = ' ';    config.filebrowserBrowseUrl =  '/ckscxz/ckfinder/ckfinder.html' ;      config.filebrowserImageBrowseUrl =  '/ckscxz/ckfinder/ckfinder.html?type=Images' ;      config.filebrowserFlashBrowseUrl =  '/ckscxz/ckfinder/ckfinder.html?type=Flash' ;      config.filebrowserUploadUrl =  '/ckscxz/ckfinder/core/connector/java/connector.java?command=QuickUpload&type=Files' ;      config.filebrowserImageUploadUrl =  '/ckscxz/ckfinder/core/connector/java/connector.java?command=QuickUpload&type=Images' ;      config.filebrowserFlashUploadUrl =  '/ckscxz/ckfinder/core/connector/java/connector.java?command=QuickUpload&type=Flash' ;      config.filebrowserWindowWidth = '1000';      config.filebrowserWindowHeight = '700';      ---------------关于破解------------------    --图片预览文字替换ckeditor/config.js    config.image_previewText = " ";    -----------------------------------    --ckfinder/ckfinder.js    --浏览服务器左下角信息不展示   下面代码注释     if (!D) this.dV().getChild(0).appendHtml(A || B || y != 4 ? t: u + "\x3c\142\x3e" + k.htmlEncode(a.ed) + "\x3c\057\142\x3e\x3c\x2f\x64\151\166\x3e");    -----------------------------------    --隐藏版权信息    找到<h4 class='message_content'>    改为<h4 style='display:none;' class='message_content'>     -----------------------------------     --避免上传文件乱码,将上传文件名以时间戳命名    解决办法:修改源码FileUploadCommand.class  getFileItemName方法

4:将ckfinder.中web.xml的servlet信心复制到web.xml中,最终项目的web.xml信息如下

<?xml version="1.0" encoding="UTF-8"?><web-app version="3.0"     xmlns="http://java.sun.com/xml/ns/javaee"     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee     http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">  <display-name>CKStrut2</display-name><!--   配置ckfinder --><servlet>        <servlet-name>ConnectorServlet</servlet-name>        <servlet-class>com.ckfinder.connector.ConnectorServlet</servlet-class>        <init-param>            <param-name>XMLConfig</param-name>            <param-value>/WEB-INF/config.xml</param-value>        </init-param>        <init-param>            <param-name>debug</param-name>            <param-value>false</param-value>        </init-param>        <load-on-startup>1</load-on-startup>    </servlet>    <servlet-mapping>        <servlet-name>ConnectorServlet</servlet-name>        <url-pattern>            /ckfinder/core/connector/java/connector.java        </url-pattern>    </servlet-mapping>    <filter>        <filter-name>FileUploadFilter</filter-name>        <filter-class>com.ckfinder.connector.FileUploadFilter</filter-class>                <init-param>                    <param-name>sessionCookieName</param-name>                    <param-value>JSESSIONID</param-value>                </init-param>                <init-param>                    <param-name>sessionParameterName</param-name>                    <param-value>jsessionid</param-value>                </init-param>    </filter>    <filter-mapping>        <filter-name>FileUploadFilter</filter-name>        <url-pattern>            /ckfinder/core/connector/java/connector.java         </url-pattern>    </filter-mapping>    <session-config>        <session-timeout>10</session-timeout>    </session-config>  <!--   配置struts -->     <filter>        <filter-name>struts2</filter-name>        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>    </filter>    <filter-mapping>        <filter-name>struts2</filter-name>        <url-pattern>*.action</url-pattern>    </filter-mapping>  <welcome-file-list>    <welcome-file>index.jsp</welcome-file>  </welcome-file-list></web-app>

5:注意,如果struts2的过滤器过的是/*,修改为.action或者.do,不然会导致,ckfinder的上传功能更不可用

6:页面应用,把texterea区域的类设置为ckeditor就可以:

//导入js    <script type="text/javascript" src="<%=basePath%>/ckeditor/ckeditor.js"></script>    <script type="text/javascript" src="<%=basePath%>/ckfinder/ckfinder.js"></script> <form action="" method="post" >   <textarea rows="20" cols="80" id="editor" name="editor" class="ckeditor" >  请再这里编辑文本   哈哈哈哈哈   </textarea>   <input type="submit" value="保存" style=" font-size: 1.2em;">   </form>

7:效果图:

这里写图片描述

0 0
原创粉丝点击