在java web应用中集成ckeditor3.5.3介绍

来源:互联网 发布:海岛奇兵兵种等级数据 编辑:程序博客网 时间:2024/05/20 02:55

OpenJWeb中集成CKEditor3.5.3在线编辑器

 

QQ:29803446

baozhengw@163.com

 

 

因为fckeditor目前已升级为ckeditor3.5.3版本,所以openjweb平台中又整合了ckeditor3.5.3,原来的fckeditor2.6仍可使用。本文具体介绍如何将ckeditor集成到自己的web应用中。

首先从网上下载ckeditor3.5.3,解压到自己的web应用的ckeditor目录中。

 

一、字体与字号

 

集成ckeditor之后,如果需要个性化定制字体列表和字号,需要打开ckeditor目录下的ckeditor.js文件,因为ckeditor默认没有宋体、仿宋等中文字体,可在ckeditor.js中找到i.font_names= 这句,修改原来的i.font_names的值,修改后的内容:

i.font_names='/u5b8b/u4f53;/u6977/u4f53_GB2312;/u4eff/u5b8b_GB2312;/u9ed1/u4f53;/u65b0/u5b8b/u4f53;Arial Black;Arial;Comic Sans MS;Courier New;Tahoma;Times New Roman;Verdana;' ;

 

字号修改:

    找到i.fontSize_sizes= 这句,此句定义了编辑器使用的字号:

i.fontSize_sizes='8/8px;9/9px;10/10px;11/11px;12/12px;14/14px;16/16px;18/18px;20/20px;22/22px;24/24px;26/26px;28/28px;36/36px;48/48px;72/72px';

如果需要增加或删除字号,可修改i.fontSize_sizes的值。

 

二、编辑器按钮

 

如果编辑器中的按钮有的需要隐藏,可修改config.js文件,config.js中,

onfig.toolbar_A =

              [

                     ['Source'],

                     ['Cut','Copy','Paste','PasteText','PasteFromWord','-','Print', 'SpellChecker', 'Scayt'],

                     ['Undo','Redo','-','Find','Replace','-','SelectAll','RemoveFormat'],

                     '/',

                     ['Bold','Italic','Underline','Strike','-','Subscript','Superscript'],

                     ['NumberedList','BulletedList','-','Outdent','Indent','Blockquote'],

                     ['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'],

                     ['Link','Unlink','Anchor'],

                     ['Image','Table','HorizontalRule','Smiley','SpecialChar','PageBreak'],

                     '/',

                     ['Styles','Format','Font','FontSize'],

                     ['TextColor','BGColor'],

                     ['Maximize', 'ShowBlocks']

              ];

这段代码是配置编辑器工具按钮的,其中’/’表示换行,每对[]套的是一组按钮,不同组的按钮之间有分隔线。

 

三、上传文件

 

Ckeditor中不再提供Java版本的文件上传和从服务器选择文件的功能,需要开发者自己实现。本节介绍上传和浏览服务器文件的具体实现方式。

首先在config.js中指定浏览服务器文件和上传文件的页面:

config.filebrowserBrowseUrl = '/portal/common/FileManager.jsp';

config.filebrowserUploadUrl = '/portal/common/uploadCK2.jsp';

config.filebrowserImageUploadUrl = '/portal/common/uploadCK2.jsp?type=Images';

 

上面分别指定了浏览服务器文件的页面FileManager.jsp,上传文件的页面uploadCK2.jsp,/portal表示当前的web应用的名字,也就是jsp中用request.getContextPath()得到的值。下面是uploadCK2.jsp的代码:

<%@page import="java.io.File"%>

<%@page import="java.util.UUID"%>

<%@page import="org.apache.commons.fileupload.FileItem"%>

<%@page import="java.util.List"%>

<%@page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>

<%@page import="org.apache.commons.fileupload.FileItemFactory"%>

<%@page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>

<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>

<!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">

<meta http-equiv="pragma" content="no-cache">

<meta http-equiv="cache-control" content="no-cache">

<meta http-equiv="expires" content="0">

<title>文件上传</title>

</head>

<body>

<%

 

String callback = request.getParameter("CKEditorFuncNum");  

String relativePath = "/userfiles/image/" ; //上传文件存储在web应用的/userfiles/image/目录中,可根据需要自己修改

 

if(ServletFileUpload.isMultipartContent(request)) //检查post到此页面的form类型是不是 enctype="multipart/form-data"类型

{

        

       String type = "";

       if(request.getParameter("type") != null)//获取文件分类

              type = request.getParameter("type").toLowerCase() + "/";

       FileItemFactory factory = new DiskFileItemFactory();

       ServletFileUpload servletFileUpload = new ServletFileUpload(factory);

       servletFileUpload.setHeaderEncoding("UTF-8");//解决文件名乱码的问题

       List<FileItem> fileItemsList = servletFileUpload.parseRequest(request);

       System.out.println(fileItemsList.size());

       for (FileItem item : fileItemsList)

       {

              if (!item.isFormField())

              {

                     String fileName = item.getName();

                  fileName = fileName.replace("//","/");

                     String fullName = fileName;

                     fileName = fileName.substring(fileName.lastIndexOf("/")+1);

                     //保存文件到服务器上

                     int i=0;

                     String tmpFileName = request.getSession().getServletContext().getRealPath(relativePath+fileName);

                     String newFile =tmpFileName;

                     File file = new File(tmpFileName);

                     if(!tmpFileName.toLowerCase().endsWith(".jpg")||

                            tmpFileName.toLowerCase().endsWith(".jpeg")||

                            tmpFileName.toLowerCase().endsWith(".bmp")||

                         tmpFileName.toLowerCase().endsWith(".gif")||

                            tmpFileName.toLowerCase().endsWith(".bmp")||

                            tmpFileName.toLowerCase().endsWith(".png")||

                            tmpFileName.toLowerCase().endsWith(".swf")||

                            tmpFileName.toLowerCase().endsWith(".doc")||

                            tmpFileName.toLowerCase().endsWith(".pdf")

                     )

                     {

                             out.println("<script type='text/javascript'>alert('服务器禁止上传此类文件!');window.parent.CKEDITOR.tools.callFunction(" 

                        + callback + ",'" + request.getContextPath()+relativePath+"blank.jpg" + "'" +")</script>");

                                    return;

                    

                     }

                     while(file.exists()) //重名的,文件名自动加1

                     {

                            if(tmpFileName.lastIndexOf(".")>-1)

                            {

                                   newFile = tmpFileName.substring(0,tmpFileName.lastIndexOf("."))+String.valueOf(++i)+"."+tmpFileName.substring(tmpFileName.lastIndexOf(".")+1);

                            }

                            else  //没有扩展名 ,不允许上传

                            {

                                    //newFile =tmpFileName+String.valueOf(++i);

                                    out.println("<script type='text/javascript'>alert('不允许上传没有扩展名的文件!');window.parent.CKEDITOR.tools.callFunction(" 

                        + callback + ",'" + request.getContextPath()+relativePath+"blank.jpg" + "'" +")</script>");

                                    return;

                            }

                            file = new File(newFile);

                       

                     }

                     if (!file.getParentFile().exists()) {

                            file.getParentFile().mkdirs();

                     }

           

                     String newFileName = newFile.replace("//","/");

                     newFileName = newFileName.substring(newFileName.lastIndexOf("/")+1);

                     item.write(file);

                     out.println("<script type='text/javascript'>window.parent.CKEDITOR.tools.callFunction(" 

                        + callback + ",'" + request.getContextPath()+relativePath+newFileName + "'" +")</script>");

                     break;

              }

       }

}

 %>

</body>

</html>

 

注意事项:

1)如果使用了struts2框架,并且在web.xml中设置了

       <filter-mapping>

              <filter-name>struts2</filter-name>

              <url-pattern>*.jsp</url-pattern>

       </filter-mapping>

需要注释掉这段代码,否则访问uploadCK2.jsp,struts2会拦截上传文件。但是如果去掉这段代码后,如果访问的url连接是直接指定的某个jsp文件,而不是.action结尾的连接,例如http://localhost:8088/portal/common/uploadCK2.jsp,则uploadCK2.jsp中不可以使用struts2标签,因为现在struts2不对.jsp结尾的做过滤了,所以jsp中的struts2标签就不起作用了。

2)在jsp指定了默认的存储文件位置为/userfiles/image/

3)上传文件如果重名,自动为文件名加1,例如aaa.jpg如果已经存在,则自动命名为aaa1.jpg,假如aaa1.jpg也存在了,会自动命名为aaa2.jpg。图见:

http://www.openjweb.com/portal/userfiles/image/help/ckupload.jpg

 

四、浏览服务器文件

本节介绍如何实现浏览服务器选择图片,插入到ckeditor的编辑区域中,openjweb的服务器浏览功能提供了用户在线管理浏览器文件夹、删除服务器端图片文件,在浏览服务器界面中可以指定图片的上传目录。

下面是配置了浏览服务器的连接后,ckeditor插入图像的弹出页面中显示了“浏览服务器”的按钮,见下图:

http://www.openjweb.com/portal/userfiles/image/help/ckbrowse1.jpg,点浏览服务器后,显示服务器端web应用下指定的某些图片目录的目录树,点选左侧的目录节点,会在右侧显示此目录下的文件。可在此界面上进行文件的上传、选择、删除、重命名、建子目录等功能,实际上还可作为一个http版的网络硬盘管理工具。下面是浏览服务器的界面:

http://www.openjweb.com/portal/userfiles/image/help/ckbrowse2.jpg

如果需要打开图片,可直接点击图片中的文件名浏览图片。

因服务器文件浏览涉及到的jsp比较多,这里不贴具体的jsp代码了。下面贴一段通过递归方式获取目录树的代码:

 

/**

        * 返回某目录下的所有的子目录

        * @param rootPath

        * @return

        */

       public static String getSubFolders(String dir,String parentHashCode)

       {

             

           String temp = "";

           File root = new File(dir);

        logger.info("父亲目录:"+dir);

           File[] filesOrDirs = root.listFiles();

        if(filesOrDirs==null)return null;

 

        String[] result = new String[filesOrDirs.length];

 

        for (int i = 0; i < filesOrDirs.length; i++)

        {

            if (filesOrDirs[i].isDirectory())

            {

                   result[i] = filesOrDirs[i].getName();

                //temp += filesOrDirs[i].getName() + ",";

                   String path = filesOrDirs[i].getAbsolutePath();

                   path = path.replace("/", "|");

                   path = path.replace("//", "|");

                  

                   temp += filesOrDirs[i].getName() +"/"+String.valueOf(filesOrDirs[i].hashCode())+"/"+parentHashCode

                   +"/"+path+",";

                   if(parentHashCode.equals("0"))

                   {

                          logger.info("子目录为:");

                       logger.info(filesOrDirs[i].getAbsolutePath());

                   }

                   temp+= getSubFolders(filesOrDirs[i].getAbsolutePath(),String.valueOf(filesOrDirs[i].hashCode()));

            }

            else 

            {

                //result[i] = filesOrDirs[i].getName();

 

               // temp += filesOrDirs[i].getName() + ",";

 

            }

        }

        //logger.info("文件目录:");

        //if(temp.endsWith(","))temp= temp.substring(0,temp.length()-1);

        logger.info(temp);

       // return temp.split(",");

        return temp;

 

       }

原创粉丝点击