Use CKEditor and Ckfinder in JSP

Source: Internet
Author: User
Tags upload php

Use CKEditor and Ckfinder in JSP

Recently in a press release platform, abandoned the early fckeditor, using CKEditor and Ckfinder, although the free Ckfinder is the demo version, but the function is complete, and users are relatively focused on the news of the people, will not care about this. According to the official website of the document step by step configuration, although not difficult, but some things are particularly scattered, or all in English, so I sorted out the installation process and configuration, as well as some issues to be aware of. We hope to help you.

Directory

1. Download CKEditor Related installation files

2. Installing CKEditor and Ckfinder

3. Use CKEditor on the web

4. Three ways to configure CKEditor

5. Some configuration options for CKEditor

6. Questions about Enter in CKEditor editor

7. Integrate Ckfinder into the CKEditor

8. Configure Ckfinder

9. Configure the Ckfinder servlet in the project

10. More secure use of Ckfinder

1. Download CKEditor Related installation files
    • CKEditor: On the left side of the Http://ckeditor.com/download page, you can download to various versions of CKEditor, including full version, Standard Edition, Basic Basic, and more. On the right-hand side of the page, there is a customizable download that lets you choose from toolbar types, plugins, languages, and more. Here we select the full version of the 4.1 version, which is ckeditor_4.1_full.zip after downloading.
    • CKEditor for Java: In the lower right part of the Http://ckeditor.com/download page, you can download to the server-side tool and remember to select the for Java version. Select the 3.6.4 version here. But downloading it is ckeditor-java-core-3.5.3.jar. I don't know why.
    • Ckfinder: On the http://cksource.com/ckfinder/trial page, you can download to various versions of Ckfinder. Still choose Java Edition. Here we download the 2.3.1 version and get ckfinder_java_2.3.1.zip after downloading.
2. Installing CKEditor and Ckfinder
    • Unzip the ckeditor_4.1_full.zip, the extracted directory CKEditor completely copied to the site root directory, that is, and Web-inf peers. You can add a version number to this directory, that is, ckeditor4.1.
    • The ckeditor4.1/samples completely deleted, the Ckeditor4.1/lang inside except En.js and zh-cn.js outside the document deleted, ckeditor4.1 under the readme.md, changes.md deleted.
    • Put the Ckeditor-java-core-3.5.3.jar under the Yourapp/web-inf/lib.
    • Unzip the Ckfinder_java_2.3.1.zip and get the Ckfinder directory. Copy the Ckfinder/ckfinderjava/ckfinder directory completely to the root of the Web site, that is, web-inf sibling. You can add a version number to this directory, that is, ckfinder2.3.1.
    • Remove the ckfinder2.3.1/_samples completely and delete the Ckfinder2.3.1/lang under the En.js and Zh-cn.js, ckfinder2.3.1 The Changelog.txt,install.txt,license.txt,translations.txt is deleted.
    • Copy all the jar packages under the Ckfinder/ckfinderjava/web-inf/lib to Yourapp/web-inf/lib.
    • Copy the Ckfinder/ckfinderjava/web-inf/config.xml to Yourapp/web-inf and rename it to Ckfinder.xml.

3. Use CKEditor on the web

STEP1: Find the page that needs to place the CKEditor editor, introduce the CKEditor js file (${contextpath} is the jstl notation, please change to your own path, absolute path or relative path)

<script type= "Text/javascript" src= "${contextpath}/ckeditor4.1/ckeditor.js" ></script>

STEP2: In the form that needs to be submitted, write a <textarea>

<form id= "Detailform" method= "POST" >    <textarea id= "content" name= "content" ></textarea>    <input type= "button" value= "Save" id= "Save" onclick= "Save ()"/></form>

STEP3: Creating an CKEditor instance

<script type= "Text/javascript" >    var editor = null;    Window.onload = function () {        editor = ckeditor.replace (' content ');//parameter ' content ' is the Name property value of the TEXTAREA element, not the ID property value    }</script>

Note that the Editor=ckeditor.repalce () in the above code must be written in the Window.onload event, or behind the textarea element, to avoid errors that do not exist in the content. The above code is not the only way to create a CKEditor instance, you can access the data yourself.

STEP4: Set/Get value for CKEditor editor in Page JS

Editor.setdata (' Here is the value that needs to be passed to the CKEditor Editor instance '); Editor.getdata ();

Note that the above code uses a variable editor, which is the editor defined in STEP3. This is why the STEP3 is to write the var editor = null code separately. Of course, setting values directly in <textarea></textarea> is also possible, but that only works before Ckeditor.replace ().

STEP5: Get the value of the CKEditor editor in the background Java code

<script type= "Text/javascript" >    function Save () {        editor.updateelement ();//Very important code        //foreground verification work        //Submit to Background    } </script>

Because the CKEditor editor replaces the original TEXTAREA element we wrote, the content that we write in the editor is not actually in textarea, so in order to get the value through textarea in the background, you must use Editor.updateelement () To update the TEXTAREA element. In this way, you can use Request.getparameter (' content ') in the background Java code, or other code to get the contents of the editor, otherwise the resulting content is probably not in the editor.

4. Three ways to configure CKEditor

Method One: Modify the Ckeditor4.1/config.js file

Ckeditor.editorconfig = function (config) {    config.language = ' ZH-CN ';    Config.uicolor = ' #AADC6E ';};

Mode two: Copy the Ckeditor4.1/config.js, still placed in the ckeditor4.1 directory, but renamed to Myconfig.js, and modify the configuration in this file. However, to indicate the configuration file path when creating an editor instance:

<script type= "Text/javascript" >    var editor = null;    Window.onload = function () {        editor = ckeditor.replace (' content ', {            customconfig: ' ${contextpath}/ckeditor4.1 /myconfig.js '        });    
</script>

Method Three: Specify the configuration when creating an editor instance

<script type= "Text/javascript" >    var editor = null;    Window.onload = function () {        editor = ckeditor.replace (' content ',             uicolor: ' #9AB8F3 ',            language: ' ZH-CN '        });    </script>

The advantage of using the second or third approach is that when you update the CKEditor version, you do not overwrite the individual configuration by copying the new config.js directly.

5. Some configuration options for CKEditor

The complete ckeditor configuration option is here. Here are some common configurations.

    • Language,defaultlanguage,contentlanguage, Uicolor
    • Autogrow_maxheight, Autogrow_minheight, Resize_maxheight, Resize_minheight, Resize_maxwidth, Resize_minWidth
    • Toolbarcancollapse, Toolbargroups
    • Forcepasteasplaintext, Pastefromwordkeepsstructure, Pastefromwordremovefontstyles, PasteFromWordRemoveStyles
    • Font_names, fontsize_sizes
6. Questions about Enter in CKEditor editor

In the CKEditor editor, hit Enter, the default is to add a <p></p> element, and before <p> and after the </p> will be added line. This creates a problem where the saved data may end up with "\t\n". When we use Editor.setdata (...) When, in fact, become a

Editor.setdata (...);

Because the data itself with a \t\n, so that the JS code line, so that the page error. There may be other ways to solve this problem, but I'm using a bar to add a newline after the carriage return <p></p>. The method is:

<script type= "Text/javascript" >    var editor = null;    Window.onload = function () {        editor = ckeditor.replace (' content ', {            customconfig: ' ${contextpath}/ckeditor4.1 /myconfig.js ', on                    : {                instanceready:function (EV) {                    this.dataProcessor.writer.setRules (' P ', {                        Indent:false,                        Breakbeforeopen:false,   //<p> without a newline                        breakafteropen:false,    //<p> Do not add the line                        Breakbeforeclose:false,  //</p> before the line                        Breakafterclose:false    //</p> followed by no newline 7});}});}    ; </script>

For more information about this section, see Http://docs.ckeditor.com/#!/guide/dev_output_format

7. Integrate Ckfinder into the CKEditor

There is no ckfinder,ckeditor as an editor and can be used normally, but it is not possible to browse users on the server in the editor to upload files. So to integrate Ckfinder.

STEP1: Introduction of Ckfinder JS file in the page

<script type= "Text/javascript" src= "${contextpath}/ckfinder2.3.1/ckfinder.js" ></script>

STEP2: Creating an Ckfinder instance

<script type= "Text/javascript" >    var editor = null;    Window.onload = function () {        editor = ckeditor.replace (' content ', {            customconfig: ' ${contextpath}/ckeditor4.1 /jwc_config.js '        });        Ckfinder.setupckeditor (editor, ' ${CONTEXTPATH}/CKFINDER2.3.1/');    }; </script>

Above the red code, the first parameter is the CKEditor instance, the second parameter is the directory of Ckfinder (preferably write absolute path), note that the last to have a slash '/'.

STEP3: Configure which page or program to browse and upload files in CKEditor

Locate the location of the configuration CKEditor in your project (see the Three Configuration Methods section of this article CKEditor), and configure the following:

Ckeditor.editorconfig = function (config) {
Some other configuration filebrowserbrowseurl = '/ckfinder2.3.1/ckfinder.html '; Filebrowserimagebrowseurl = '/ckfinder2.3.1/ckfinder.html?type=images '; Filebrowserflashbrowseurl = '/ckfinder2.3.1/ckfinder.html?type=flash '; Filebrowseruploadurl = '/ckfinder2.3.1/core/connector/java/connector.java?command=quickupload&type=files '; Filebrowserimageuploadurl = '/ckfinder2.3.1/core/connector/java/connector.java?command=quickupload&type= Images '; Filebrowserflashuploadurl = '/ckfinder2.3.1/core/connector/java/connector.java?command=quickupload&type= Flash ';};

The above six lines of code, specified through ckfinder2.3.1/ckfinder.html to browse pictures or other files, through the/ckfinder2.3.1/core/connector/java/connector.java to upload files.

8. Configure Ckfinder

Find the Yourapp/web-inf/ckfinder.xml and edit the contents. The following is a brief introduction to the meaning of each item, other than what is not covered in the ckfinder.xml itself, please refer to the comments and here.

    • Enabled:true indicates that the Ckfinder function is turned on. The default is False.
    • BaseDir: The path where the file is uploaded, the full path from the physical address, such as C:\myapp\uploadfiles\, must be written here. You cannot write a relative path, and you must add a slash "/" at the end. This item can not be configured, if left blank, the system will automatically find Basedir according to BaseURL. But the recommendation is better than the configuration.
    • BaseURL: Upload a file to store the URL, here can write a relative path or a complete URL, such as "http://www.example.com/uploadfiles/" or "/uploadfiles/". Note, be sure to add a slash "/" at the end. See here for more explanations.
    • Types: Specifies the type of file to upload. Its child element is <type name= "" ></type>, where the name is identical to the type of the path configured in CKEditor above. For example, the above configuration Filebrowserimagebrowseurl = ' ckfinder2.3.1/ckfinder.html?type=images ', then must be equipped with a <type name= "Images" > </type>. In the <type></type> element, you can configure subdirectories (placed under Basedir), sub-URLs, maximum number of bytes of files, file extensions that are allowed to be uploaded, and file extensions that are forbidden to be uploaded.
    • Disallowunsafecharacters: Set to False. If set to True, the name cannot contain unsafe characters when creating a folder or uploading a file. This only takes effect in IIS.
    • Checkdoubleextension: Check the multilevel extension, perhaps you prohibit users to upload PHP files, allowing users to upload rar files. If this is set to False, the file Foo.php.rar is uploaded to the server, which is not secure. Therefore, this key is set to true.
    • Secureimageuploads: Set this to True, you can check whether the file is not a picture, it is possible that someone has added an executable file suffix into a. jpg, but in fact it is not a picture file.
9. Configure the Ckfinder servlet in the project

Locate Yourapp/web-inf/web.xml, and add the following:

<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/ckfinder.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>/ckfinder2.3.1/core/connector/java/connector.java </url-pattern> </servlet-mapping>

The first init-param in the above configuration is the configuration file location for the specified ckfinder. That is the configuration file mentioned in part 8th above.

10. Safer to use Ckfinder

For now, Ckfinder can be used normally. However, even if you do not have administrative privileges on your project, enter yoursite/ckfinder2.3.1/ckfinder.html in the browser, you can also see the files stored on your server, they can even upload and delete files. There are two places to enhance the safety of ckfinder.

Configure access Permissions in Yourapp/web-inf/ckfinder.xml
<userRoleSessionVar>CKFinder_UserRole</userRoleSessionVar><accessControls>    < accesscontrol>        <role>admin</role>        <resourceType>*</resourceType>        < folder>/</folder>        <folderView>true</folderView>        <foldercreate>true</ foldercreate>        <folderRename>true</folderRename>        <folderdelete>false</ folderdelete>        <fileView>true</fileView>        <fileUpload>true</fileUpload>        <fileRename>true</fileRename>        <fileDelete>false</fileDelete>    </ Accesscontrol></accesscontrols>

Then in the Java code in the appropriate location, such as the login () method, add the following code

Request.getsession (). SetAttribute ("Ckfinder_userrole", "admin");

When you access yoursite/ckfinder2.3.1/ckfinder.html (including the Browse Server button clicked), you check what the value of Ckfinder_userrole is and what permissions it has. If a person does not log on to the system and accesses yoursite/ckfinder2.3.1/ckfinder.html directly, then the system checks that ckfinder_userrole is null and he cannot see the files on the server.

Self-write code checks if the user has permission to use Ckfinder

In Yourapp/web-inf/web.xml, modify the configuration about Ckfinder and add a piece of code:

 <servlet> <servlet-name>ConnectorServlet</servlet-name> <servlet-class>com.ckfinder . Connector.        Connectorservlet</servlet-class> <init-param> <param-name>configuration</param-name> <param-value>mypackage. ckfinderconfiguration</param-value> </init-param> <init-param> <param-name>xmlconfig </param-name> <param-value>/WEB-INF/ckfinder.xml</param-value> </init-param> <i     Nit-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>/ckfinder2.3.1/core/connector/java/ Connector.java </url-pattern> </servlet-mapping> 

Create a class Ckfinderconfiguration under package path MyPackage (the package path and class name are named according to the organization of your project code), the code is as follows:

Import com.ckfinder.connector.configuration.Configuration;
public class Ckfinderconfiguration extends Configuration {public ckfinderconfiguration (servletconfig ServletConfig) { super (servletconfig); } @Override protected Configuration createconfigurationinstance () { return new ckfinderconfiguration ( this.servletconf); } @Override Public Boolean checkauthentication (final HttpServletRequest request) { String UserID = Request.getsession (). getattribute ("userid"); Boolean logined =!userid.equals (""); return logined;} }

The key is the Checkauthentication () method. Some judgments about user authentication can be written in the Checkauthentication () method, such as whether the user is logged on to the system or whether the user has permission to manage the upload file. Returns ture if the condition is met, otherwise false.

Both of these methods make ckfinder more secure and, of course, better to use at the same time. But pay attention to the difference, the latter can only be in a relatively coarse granularity control.

Use CKEditor and Ckfinder in JSP

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.