Configuration and use of FCKeditor

Source: Internet
Author: User
Tags mkdir uuid browser cache tomcat server

FCKeditor Introduction:
FCKeditor is a WYSIWYG text editor that is specifically designed to be in the open source code on a Web page. It is focused on lightweight and does not require too complex installation steps to be used. It can be combined with different programming languages such as PHP, JavaScript, ASP, ASP.net, ColdFusion, Java, and ABAP. The "FCK" in the "FCKeditor" name is the initials of the author of this editor Frederico Caldeira Knabben. FCKeditor is compatible with most Web browsers.
If you want to run the FCKeditor, first need a jar bag, and fckeditor_2.6.4.1.zip, these people can go to the Www.fckeditor.net official website download, here's the need for the jar bag I give you list:
Commons-fileupload-1.2.1.jar
Commons-io-1.3.2.jar
Fckeditor-java-core-2.4.jar
Java-core-2.4.jar
Slf4j-api-1.5.2.jar
Slf4j-simple-1.5.2.jar
There are resources on the CSDN, and everyone can download it.
Next how to call FCKeditor. There are two ways: using JavaScript calls and JSP's custom tags
Place the extracted fckeditor_2.6.3 under the Webroot of the Web project
Then create a new HTML in which to introduce the fckeditor.js in the FCKeditor folder, introducing the following: <script type= "Text/javascript" src= "Fckeditor/fckeditor.js" >
Next: Introduce the first method:
<script type= "Text/javascript" >
var fckeditor=new fckeditor (' FCKeditor1 ');/create a new FCKeditor instance
FCKeditor. Basepath= "/fckeditor/"; the position of the editor, which must be at/end, this basepath refers to the address of all files under the FCKeditor folder, the default is this, but we generally have to add the name of the project, such as/prj/ fckeditor/this
FCKeditor. Create ();//Creates and invokes a FCKeditor editor
</script>

The second method is to complete the call through the JSP custom label
can refer to:
@ Demo Project Fckeditor-java-demo-2.4.war:jsp folder--"sample02.html
@fckeditor-java-2.4 Document
<%@ taglib= "Http://java.fckeditor.net"%>
<fck:editor instancename= "Myeditor" basepath= "/fckeditor" value= "This is value" ></FCK:editor><!-- Note that you must write the value value here, and it cannot be an empty string-->
Note: BasePath with/beginning, and this/represents the current project path
After completing the above steps, you can access the HTML file through the browser, you will see a simple FCKeditor interface, but many things still need to configure their own to use

First you can go to www.fckeditor.net official website download Fckeditor-java-demo-2.4.war and then directly to Tomcat, you can browse the page in the browser http://localhost:8080/ fckeditor-java-demo-2.4/
Also download Fckeditor_2.6.4.1.zip and Fckeditor-java-2.4-bin.zip

Configuration--Using a configuration file
Fckconfig.js is the main configuration file, if we want to modify the configuration, we need to modify the properties of the file, we can directly modify the profile, but we do not take this approach, generally we are a new configuration file myconfig. JS to overwrite the default configuration file
For example, we created a new myconfig.js and then wrote the Fckconfig.autodetectlanguage=false in it; Fckconfig.defaultlanguage= ' fr ' Changes the automatic discovery language in the original configuration file to False and specifies the default language as French FR
So when we finish writing the configuration file, what if it's applied. There are two ways of doing this:

1) in the original configuration file in the Fckconfig.js fckconfig.customconfigurationpath= ' changed to Fckconfig.customconfigurationpath= '/fck/ Myconfig.js '
Note: This method modifies all properties of the FCKeditor page
2) in the page to make. Add the following statement to the code that calls FCK: FCKeditor. config["Customconfigurationspath"]= "/test/myconfig.js";
Note: This method will only modify the FCKeditor properties of the page, the general project when the release is not sure where, so test should be replaced with Fckeditor.editorpath, which refers to the FCKeditor folder under the Editor folder
Summarize the configuration FCKeditor:

1) directly modify the main configuration file, Fckconfig.js
2 Define a separate configuration file (only need to write configuration items that need to be modified)
3 Configure the FCKeditor instance in the page's code
To configure the load order:
1 Load the main configuration file Fckconfig.js
2 Load the custom profile (if any), overwriting the same configuration item (note is the same)
3 Overwrite the same configuration item with the configuration of the instance (valid only for the current instance)
Precautions:
1. Never delete a master profile: Fckconfig.js
2. The system will automatically detect and run the appropriate interface language (default, you can modify)
3. After modifying the configuration to clear the browser cache, so as not to affect the results (or forced refresh when Access can also)

Configurations that need to be modified generally
1 Custom ToolbarSet, remove some features
2) plus a few commonly used fonts
3) Modify the "carriage return" and "shift+ return" of the line behavior: The original FCK of the return key effect is to change the paragraph, and the effect of shift+ carriage returns is a line, so we want to put the two effects upside down
4) Modify the edit area style file
5) Change the expression picture

About setting ToolbarSet: First in fckconfig.js find fckconfig.toolbarsets[] You can specify the name of toolbar in parentheses, such as Mytoolbar, Then, on the page that calls FCK, set the ToolbarSet to Mytoolbar that fckeditor. Toolbarset= "Mytoolbar", so it's OK.

About adding several fonts: Just add the font we want to add to the fckconfig.fontnames and note that it prompts you not to save, set the text file encoding in the Resources option for Myconfig.js file properties And can only be set to Utf-8


About modifying carriage return line wrap:
Fckconfig.shiftentermode = ' P '; P | div | Br
Fckconfig.entermode = ' BR '; P | div | Br
Instead of switching between the two lines,

About the Edit area style file: In the main configuration file Fckconfig.js file, find fckconfig.editorareacss = Fckconfig.basepath + ' css/fck_editorarea.css ';
We'll find that all the styles are in the Fck_editorarea.css file under the CSS folder under the Editor folder,

About adding a custom expression:
fckconfig.smileypath = Fckconfig.basepath + ' images/smiley/msn/';//= the folder where the expression is located
fckconfig.smileyimages = [' regular_smile.gif ', ' sad_smile.gif ', ' wink_smile.gif ', ' teeth_smile.gif ', ' confused _smile.gif ', ' tounge_smile.gif ', ' embaressed_smile.gif ', ' omg_smile.gif ', ' whatchutalkingabout_smile.gif ', ' Angry_ Smile.gif ', ' angel_smile.gif ', ' shades_smile.gif ', ' devil_smile.gif ', ' cry_smile.gif ', ' lightbulb.gif ', ' Thumbs_ Down.gif ', ' thumbs_up.gif ', ' heart.gif ', ' broken_heart.gif ', ' kiss.gif ', ' envelope.gif '; each picture in the folder, whose contents are arrays
Fckconfig.smileycolumns = 8;//Indicates the number of emoticons displayed per column
Fckconfig.smileywindowwidth= 320;//Indicates the width of the pop-up dialog box
fckconfig.smileywindowheight= 210;//Indicates the height of the pop-up dialog box

If we want to add a picture of our own to the expression, first copy the picture to the folder, and then add the name of the picture in the array, you can
You can also use a picture folder of your own as an emoticon folder, you need to specify Smileypath as our own picture folder, and then list each picture name in the folder in the array
At this time we may encounter, if the picture is too much, it will show a long, very long, even if we set the Smileywindowwidth and Smileywindowheight is not used, when we right-click, view its source file, should be http://localhost : 8080/fck/fckeditor/editor/dialog/fck_smiley.html this HTML, and then we find the open, Window.onload event dialog.setautosize (true); We will change it to false, which will be shown in accordance with the width of our designation, but will be a lot less picture expression, so we have to <body style= "Overflow:hidden" > here, the hidden will be changed to scroll, If the picture is too large to be displayed at the specified width, scroll bars are added automatically

Last hint,: Fckconfig.basepath and call FCKeditor when the BasePath (FCKeditor bathpath) specified is not the same and its value is not the same

File upload: This is very common.
We can refer to d:/java/fckeditor/fckeditor-java-2.4-bin/fckeditor-java-2.4/site/connector.html, the file,

First step:
Declare the Connectorservlet in your web.xml
  <web-app version= "2.4"
    <servlet>
      <servlet-name>connector</servlet-name>
         <servlet-class>
           Net.fckeditor.connector.ConnectorServlet
      </servlet-class>
      <load-on-startup>1</load-on-startup>
    </ Servlet>
    <servlet-mapping>
      <servlet-name> Connector</servlet-name>
      <url-pattern>
        /fckeditor/editor/filemanager/connectors/*
      </ Url-pattern>
    </servlet-mapping>
  </WEB-APP>
configuration file

Step Two:
Under the engineering SRC, create a new Fckeditor.properties file with the following contents:
Connector.useractionimpl=net.fckeditor.requestcycle.impl.useractionimpl

So you can simply use the upload

In the upload file name is Chinese when the name will appear garbled, how to solve.
The first thing to know is that this garbled text may be submitted to the content of the incorrect coding problem, or submitted to the server side of the problem of processing
First, we find the corresponding editor->filemanager->default->. Frmupload.html we found that it was shown in Utf-8 code, no problem, and then we look at the love you gave to which file to deal with, in the Web.xml file we just configured has already specified Net.fckeditor.connector.ConnectorServlet, is This, the servlet is fckeditor-java-core below the referenced libraries. NET under the JAR package. FCKeditor Connector under the servlet, and then we want to attach source, associated with the source code, the source is Fckeditor-java-2.4-src.zip, finished, press Ctrl+o, and then see its Dopost method, in list< Fileitem> item=upload.parserequest (request); Here is the code that needs to be specified. But this file we can not modify, so to copy over, under SRC Create a new package, the same name of the servlet, and then paste, before try write: upload.setheaderencoding ("Utf-8"); Then you must modify the in the Web.xml file
<servlet-class>
Net.fckeditor.connector.ConnectorServlet Modify here, change the name of the previous package
</servlet-class>

In addition, there will be garbled when the Chinese directory name is created
Still in the Connectorservlet file in the Doget method, locate the Newfoldname and add the following:
String tempstr=request.getparameter ("Nowfoldname");
Tempstr=new String (temstr.getbytes ("iso8859-1"), "Utf-8");
String newfoldstr= ... (TEMPSTR)

Pictures that refer to Chinese names are not displayed correctly.
Method One: Modify the configuration of the Tomcat connector:tomcat6.0-->conf-->server.xml-->
<connector executor= "Tomcatthreadpool"
port= "8080" protocol= "http/1.1"
connectiontimeout= "20000"
Redirectport= "8443"
Add an attribute after this: uriencoding= "Utf-8"
After the modification, you will need to restart the Tomcat server, but this method does not recommend the use of

Method Two: Avoid the use of the Chinese name of the picture, that is, in the Chinese name of the picture to save, so that it is not in Chinese format, change to the UUID encoding method
In the Connectorservlet file, locate the file where you saved the Dopost method, Pathtosave and then add the following:
Filename=uuid.randomuuid (). toString () + "." +extension;

The above tells the comparison theory, everybody can I have already configured the Connectorservlet class, the code is as follows:
Package net; Import java.io.*; Import javax.servlet.*; Import javax.servlet.http.*; Import java.util.*; Import Java.util.regex.Pattern; Import org.apache.commons.fileupload.*; Import javax.xml.parsers.*; Import org.w3c.dom.*; Import javax.xml.transform.*; Import Javax.xml.transform.dom.DOMSource; Import Javax.xml.transform.stream.StreamResult; public class Connectorservlet extends HttpServlet {private static String BaseDir; private static Boolean debug = FALSE; /allow upload of the image type of the file type private static String Allowedtype; File class rows that are not allowed to upload are private static String unallowedfiletype; /** * initializes the servlet. * Retrieve from the servlet configuration The "BaseDir" which are the root * of the file repository: * If not specified the The value of "/userfiles/" would be used. * */public void init () throws servletexception {BaseDir = Getinitparameter ("BaseDir"); debug = (New Boolean (Getinitparam Eter ("Debug")). Booleanvalue (); Sets the default value of BaseDir if (BaseDir = = null) BaseDir = "/userfiles/"; String Realbasedir= Getservletcontext (). Getrealpath (BaseDir); File Basefile = new file (Realbasedir); Create the directory if (!basefile.exists ()) {Basefile.mkdir ();}//Get the image type that is allowed to upload, from web.xml configuration Allowedtype = "|jpg|gif|jpeg|png|bmp|" ; Unallowedfiletype = "ABC"; /** * Doget Method Processing (getfolders, Getfoldersandfiles, CreateFolder). * This servlet receives the following parameter * connector? Command=commandname&type=resourcetype&currentfolder=folderpath * It finally returns the XML/public void doget ( HttpServletRequest request, HttpServletResponse response) throws Servletexception, IOException { Response.setcontenttype ("Text/xml; Charset=utf-8 "); Response.setheader ("Cache-control", "No-cache"); PrintWriter out = Response.getwriter (); String commandstr = Request.getparameter ("Command"); Gets the file type, Image,file,flash,media String typestr = Request.getparameter ("type"); Gets the current directory String currentfolderstr = Request.getparameter ("CurrentFolder"); Get the real path of the current directory String Currentpath = baseDir + typestr + currentfolderstr; String Currentdirpath = Getservletcontext (). getreAlpath (Currentpath); Creates the current path file Currentdir = new file (Currentdirpath); if (!currentdir.exists ()) {Currentdir.mkdir ();}///create returned XML file document = NULL; try {documentbuilderfactory factory = documentbuilderfactory. newinstance (); Documentbuilder builder = Factory.newdocumentbuilder (); Document = Builder.newdocument (); catch (parserconfigurationexception PCE) {pce.printstacktrace ();} Node root = Createcommonxml (document, Commandstr, Typestr, Currentfolderstr, Request.getcontextpath () + Currentpath); Gets the user-selected directory if (commandstr.equals ("Getfolders")) {Getfolders (Currentdir, Root, document);}//Get the files of the user-selected directory else if (COM Mandstr.equals ("Getfoldersandfiles")) {Getfolders (Currentdir, Root, document); GetFiles (Currentdir, Root, document);} New directory else if (commandstr.equals ("CreateFolder")) {String newfolderstr = Request.getparameter ("NewFolderName"); When uploading, create a folder when garbled problem resolution Newfolderstr=new String (Newfolderstr.getbytes ("iso8859-1"), "UTF-8"); File NewFolder = new file (cuRrentdir, NEWFOLDERSTR); System.out.println (newfolderstr+ "folder"); String RetValue = "110"; You can enter only English character numbers or underscores if (! Pattern.matches ("//w+", Newfolderstr)) {RetValue = "102";}//directory already exists else if (newfolder.exists ()) {RetValue = "101";} Create a new directory else {try {boolean dircreated = Newfolder.mkdir (); if (dircreated) RetValue = "0"; Else RetValue = "102";} CA TCH (SecurityException Sex) {sex.printstacktrace (); retvalue = "103";}} Setcreatefolderresponse (RetValue, Root, document); } document.getdocumentelement (). normalize (); try {transformerfactory tfactory = transformerfactory.newinstance (); Transformer Transformer = Tfactory.newtransformer (); Domsource Source = new Domsource (document); Streamresult result = new Streamresult (out); Transformer.transform (source, result); if (Debug) {Streamresult Dbgresult = new Streamresult (System.out); Transformer.transform (source, Dbgresult);}} catch (Exception ex) {//Ex.printstacktrace ();} out.flush (); Out.close (); /** * Process File Upload * * This servlet receives suchNext parameter: * connector? Command=fileupload&type=resourcetype&currentfolder=folderpath */public void DoPost (httpservletrequest Request, HttpServletResponse response) throws Servletexception, IOException {response.setcontenttype ("text/html; Charset=utf-8 "); Response.setheader ("Cache-control", "No-cache"); PrintWriter out = Response.getwriter (); String commandstr = Request.getparameter ("Command"); Gets the file type, Image,file,flash,media String typestr = Request.getparameter ("type"); Get current directory String currentfolderstr = Request.getparameter ("CurrentFolder"); Get the current real path String Currentpath = baseDir + typestr + currentfolderstr; String Currentdirpath = Getservletcontext (). Getrealpath (Currentpath); String RetVal = "0"; String newName = ""; if (!commandstr.equals ("FileUpload")) RetVal = "203"; else {///generated upload object, and set compile diskfileupload upload = new Diskfileupload (); Upload.setheaderencoding ("UTF-8"); try {List items = Upload.parserequest (request); Map fields = new HashMap (); Iterator iter = items.itErator (); while (Iter.hasnext ()) {Fileitem item = (Fileitem) iter.next (); if (Item.isformfield ()) Fields.put (Item.getfieldname (), Item.getstring ()); Else Fields.put (Item.getfieldname (), item); } Fileitem Uplfile = (fileitem) fields.get ("NewFile"); String Filenamelong = Uplfile.getname (); Filenamelong = Filenamelong.replace ('//', '/'); string[] Pathparts = Filenamelong.split ("/"); String fileName = pathparts[pathparts.length-1]; String ext = getextension (fileName); To prevent the Chinese picture from being read correctly, change the picture name to the UUID encoding format filename=uuid.randomuuid () before saving. ToString () + "." +ext; String Namewithoutext = getnamewithoutextension (fileName); File Pathtosave = new file (Currentdirpath, fileName); System.out.println ("Pathtosave" +pathtosave); int counter = 1; int limitedsize=70*1024;//Limit the size of uploaded Pictures//Check whether the file type that is allowed to upload is image, then check the file type in Web.xml configure if (This.checkimagetype (allowedtype , fileName)) && {retVal = "typestr.equals";//System.out.println ("DD");} else if (THIS.CHECKFI Letype (Unallowedfiletype, FilenaMe) && (Typestr.equals ("File")) {//System.out.println ("Ddee"); retVal = "202";}//If file size exceeds limit, return a custom error code El Se if (uplfile.getsize () >limitedsize) {retval= "204";} else {while (pathtosave.exists ()) {newName = Namewithoutext + "(" + Counter + ")" + "." + ext; Newname=uuid.randomuuid (). toString () + "." +ext; RetVal = "201"; Pathtosave = new File (Currentdirpath, newName); counter++; System.out.println ("Namewithoutext:" +namewithoutext);} Uplfile.write (Pathtosave); The catch (Exception ex) {ex.printstacktrace (); retVal = "203";}} Out.println ("<script type= '/" text/javascript/"' >"); Out.print ("<mce:script language= ' javascript ' ><!--window.parent.frames[' frmupload ')." Onuploadcompleted ("+retval +", ' "+ NewName +"); --></mce:script> "); Out.println ("window.parent.frames[' Frmupload ')." Onuploadcompleted ("//+ RetVal +", ' "+ NewName +"); "); Out.println ("</SCRIPT>"); Out.flush (); Out.close (); } private void Setcreatefolderresponse(String RetValue, Node root, Document doc) {Element Myel = doc.createelement ("Error"); Myel.setattribute ("number", RetValue); Root.appendchild (Myel);} private void Getfolders (File dir, Node root, Document doc) {Element folders = doc.createelement ("folders"); root.appendch ILD (folders); file[] filelist = Dir.listfiles (); for (int i = 0; i < filelist.length ++i) {if (Filelist[i].isdirectory ()) {Element Myel = doc.createelement ("folder") ; Myel.setattribute ("Name", Filelist[i].getname ()); Folders.appendchild (Myel); }} private void GetFiles (File dir, Node root, Document doc) {Element files = doc.createelement ("files"); root.appendch ILD (files); file[] filelist = Dir.listfiles (); for (int i = 0; i < filelist.length ++i) {if (Filelist[i].isfile ()) {Element Myel = doc.createelement ("File"), Myel. SetAttribute ("Name", Filelist[i].getname ()); Myel.setattribute ("Size", "" + filelist[i].length ()/1024); Files.appendchild (Myel); }} private Node Createcommonxml (Document doc, StriNg Commandstr, String typestr, String Currentpath, String currenturl) {Element root = doc.createelement ("Connector"); doc . appendchild (Root); Root.setattribute ("command", COMMANDSTR); Root.setattribute ("ResourceType", typestr); Element Myel = doc.createelement ("CurrentFolder"); Myel.setattribute ("path", Currentpath); Myel.setattribute ("url", Currenturl); Root.appendchild (Myel); return root; /** * Get filename, no extension * * * * @param filename * @return/private static string Getnamewithoutextension (String fileName) { Return filename.substring (0, Filename.lastindexof (".")); /** * Get File extension * * @param filename * @return/private string GetExtension (string fileName) {return filename.substring (Filename.lastindexof (".") + 1); /** * Check the file type of upload image type, according to web.xml configuration information * * * * @param type * @param fileName * @return/Private Boolean Checkimagetyp E (String type, String fileName) {System.out.println (type+ "type"); string[] ss = Type.split ("//|"); System.out.println (ss+ "SS"); if (Type.length (); 0 {for (int i = 0; i < ss.length i++) {if (This.getextension (fileName). Equalsignorecase (Ss[i])) {return false;}/ /System.out.println (ss[i]); } return true; /** * Verify that files of file type not allowed to be uploaded * * * @param type * @param fileName * @return/private Boolean Checkfiletype (String type, stri ng FileName) {string[] ss = Type.split ("//|"); if (Type.length () > 0) {for (int i = 0; i < ss.length; i++) {if (t His.getextension (FileName). Equalsignorecase (Ss[i])) {return true;}//System.out.println (Ss[i]); System.out.println (FileName); return false; } }

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.